﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Common;
using DFGK_WMS.Model.Dto;
using DFGK_WMS.Model.Dto.YS;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Hosting;
using Microsoft.VisualBasic;
using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace DFGK.Service
{
    public class ReceivingOrderDetailService : BaseService, IReceivingOrderDetailService
    {
        private readonly IReceivingOrderDetailRepository _receivingOrderDetailRepository;
        private readonly IReceivingBillDetailRepository _receivingBillDetailRepository;
        private readonly IPutawayOrderDetailRepository _putawayOrderDetailRepository;
        private readonly IPickingOrderDetailRepository _pickingOrderDetailRepository;
        private readonly IMaterialPackageRepository _materialPackageRepository;
        private readonly IShippingLockCellRepository _shippingLockCellRepository;
        private readonly IStackingStorageRepository _stackingStorageRepository;
        private readonly ISupplierRepository _supplierRepository;
        private readonly IDepartMentRepository _departMentRepository;
        private readonly IOtherTypeRepository _otherTypeRepository;
        private readonly IInventoryDetailRepository _inventoryDetailRepository;
        private readonly IStockRepository stockRepository;
        private readonly IReceivingBillRepository _receivingBillRepository;
        private readonly IPutawayOrderRepository _putawayOrderRepository;
        public readonly  IPackageDetailRepository _PackageDetailRepository;
        private readonly IPickingOrderRepository _pickingOrderRepository;
        private readonly IInventoryLogRepository _inventoryLogRepository;
        private readonly IInterfaceLogRepository _interfaceLogRepository;
        private readonly IWarehouseRepository _warehouseRepository;
        private readonly IInventoryRepository _inventoryRepository;
        private readonly IRoutewayRepository _routewayRepository;
        private readonly IInstructRepository _instructRepository;
        private readonly HttpClientHelper _httpClientHelper;
        private readonly IMaterialRepository _materialRepository;
        private readonly IStationRepository _stationRepository;
        private readonly IPalletRepository _palletRepository;
        private readonly IShelfRepository _shelfRepository;
        
        private readonly ICellRepository _cellRepository;
        private readonly IAreaRepository _areaRepository;
        private readonly WcsHttpClient _wcsHttpClient;
        private readonly IUnitOfWork _unitOfWork;
        public ReceivingOrderDetailService(IMapper mapper, IReceivingBillRepository _receivingBillRepository, IReceivingOrderDetailRepository _receivingOrderDetailRepository, IReceivingBillDetailRepository _receivingBillDetailRepository, IPalletRepository _palletRepository, IUnitOfWork _unitOfWork, IStationRepository stationRepository, IStackingStorageRepository _stackingStorageRepository, IWarehouseRepository warehouseRepository, IAreaRepository areaRepository, IRoutewayRepository routewayRepository, IShelfRepository shelfRepository, ICellRepository cellRepository, IInventoryRepository inventoryRepository, IInstructRepository _instructRepository, IPutawayOrderRepository putawayOrderRepository, IPutawayOrderDetailRepository putawayOrderDetailRepository, IInventoryDetailRepository inventoryDetailRepository, IInventoryLogRepository inventoryLogRepository, IMaterialRepository materialRepository, IShippingLockCellRepository shippingLockCellRepository, IPickingOrderRepository _pickingOrderRepository, IPickingOrderDetailRepository _pickingOrderDetailRepository, WcsHttpClient _wcsHttpClient, IMaterialPackageRepository _materialPackageRepository, IInterfaceLogRepository _interfaceLogRepository, IPackageDetailRepository packageDetailRepository, IMaterialPackageRepository materialPackageRepository, IStockRepository stockRepository, ISupplierRepository supplierRepository, IOtherTypeRepository otherTypeRepository, HttpClientHelper httpClientHelper, IDepartMentRepository departMentRepository) : base(mapper)
        {
            this._receivingOrderDetailRepository = _receivingOrderDetailRepository;
            this._receivingBillDetailRepository = _receivingBillDetailRepository;
            this._pickingOrderDetailRepository = _pickingOrderDetailRepository;
            this._stackingStorageRepository = _stackingStorageRepository;
            this._materialPackageRepository = _materialPackageRepository;
            this._receivingBillRepository = _receivingBillRepository;
            this._pickingOrderRepository = _pickingOrderRepository;
            this._interfaceLogRepository = _interfaceLogRepository;
            this._instructRepository = _instructRepository;
            this._palletRepository = _palletRepository;
            this._wcsHttpClient = _wcsHttpClient;
            this._unitOfWork = _unitOfWork;
            _putawayOrderDetailRepository = putawayOrderDetailRepository;
            _shippingLockCellRepository = shippingLockCellRepository;
            _inventoryDetailRepository = inventoryDetailRepository;
            _putawayOrderRepository = putawayOrderRepository;
            _inventoryLogRepository = inventoryLogRepository;
            _inventoryRepository = inventoryRepository;
            _warehouseRepository = warehouseRepository;
            _materialRepository = materialRepository;
            _routewayRepository = routewayRepository;
            _stationRepository = stationRepository;
            _shelfRepository = shelfRepository;
            _areaRepository = areaRepository;
            _cellRepository = cellRepository;
            _PackageDetailRepository = packageDetailRepository;
            this._materialPackageRepository = materialPackageRepository;
            this.stockRepository = stockRepository;
            _supplierRepository = supplierRepository;
            _otherTypeRepository = otherTypeRepository;
            _httpClientHelper = httpClientHelper;
            _departMentRepository = departMentRepository;
        }

        private void ModifyReceiving(ReceivingBillOrderDto m)
        {
            var receivingBills = _receivingBillRepository.QueryEntityById(m.Id);
            if (receivingBills.StockCode == null && receivingBills.StockName == null)
            {
                receivingBills.StockCode = m.StockCode;
                receivingBills.StockName = m.StockName;
                _receivingBillRepository.UpdEntity(receivingBills);
                _unitOfWork.SaveChangesEntity();
            }
            

        }
        public bool AddReceivingOrderDetail(ReceivingBillOrderDto m, out string message)
        {
            message = "";
            long aaid = 0;
           
            var aaCode = string.Empty;
            string palletBarcode = "";
            decimal receivedQty = 0;

            ModifyReceiving(m);

            var stackobj = _stackingStorageRepository.QueryEntityWhere(x => x.PalletBarcode == m.PalletBarcode);
            if (stackobj != null)
            {
                message = "改托盘正在作业中！";
                return false;
            }
            var receivingBills = _receivingBillRepository.QueryEntityById(m.Id);
            if (receivingBills == null)
            {
                message = "收货单不存在";
                return false;
            }
            var receivingBillDetails = _receivingBillDetailRepository.QueryEntityWhere(x => x.BillId == receivingBills.Id);
            if (receivingBillDetails == null)
            {
                message = "收货单明细";
                return false;
            }
            
            var receivingBill = _receivingBillRepository.QueryEntityWhere(d => d.Id == m.Id);
            if (receivingBill != null)
            {
                var area = _areaRepository.QueryEntityWhere(d => d.WhCode == receivingBill.WarehouseCode);
                aaid = area.Id;
                receivingBillDetails.AreaId = aaid;
                aaCode = area.Code;

            }
            receivingBillDetails.StoLocation = m.StoLocation;
            var inventoryobj = _inventoryRepository.QueryEntityWhere(x => x.PalletBarcode == m.PalletBarcode);
            
            if (inventoryobj != null)
            {
                if (inventoryobj.AreaCode.Contains("L"))
                {
                    if (inventoryobj.PalletBarcode != "0")
                    {
                        if (inventoryobj.Status == 1)
                        {
                            message = "该托盘已经在库存中！";
                            return false;
                        }
                    }
                   
                }
                //else
                //{
                //    receivingBillDetails.StoLocation = inventoryobj.LocationCode;
                //}                
            }
            _unitOfWork.BeginTransaction();
            try
            {
                if (m.ReceivedQty <= 0)
                {
                    message = "收货数量不能小于等于0";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                if (m.ReceivedQty % 1 != 0)
                {
                    message = "收货数量包含小数";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                if (aaCode.Contains("L"))
                {
                    if (string.IsNullOrEmpty(m.PalletBarcode))
                    {
                        message = "托盘为空";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                }
              
                if (m.ReceivedQty > (receivingBillDetails.Qty - receivingBillDetails.ReceivedQty) )
                {
                    message = "收货数量不能大于物料数量";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                else
                {
                    receivingBillDetails.ReceivedQty += m.ReceivedQty;
                }
                _receivingBillDetailRepository.UpdEntity(receivingBillDetails);
            
                palletBarcode = m.PalletBarcode;
                receivedQty = m.ReceivedQty;
                var palletbarobj = _palletRepository.QueryIsEntityWhere(x => x.PalletBarcode == palletBarcode);
                if (aaCode.Contains("L"))
                {
                    if (palletbarobj == null || palletbarobj.Status == 0)
                    {
                        message = "未查询到此托盘" + palletBarcode;
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                }
               
                //palletbarobj.LoadFactor = m.LoadFactor; //----用不到满载率
                //_palletRepository.UpdEntity(palletbarobj);//用不到更细托盘表
                bool reresult = false;
             
                if (receivingBillDetails.ReceivedQty == receivingBills.TotalQty)
                {
                    //全部收货完成
                    reresult = AddReceivingOrderDetail(receivingBillDetails, receivedQty, m.NowUserId, m.NowUserName, palletBarcode, out message);
                    if (!reresult)
                    {
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    receivingBills.Status = 2;
                   var AllPack= _PackageDetailRepository.GetEntityAlls().Where(d => d.OrderSn == receivingBills.BillNo).ToList();
                    foreach (var item in AllPack)
                    {
                        item.Status = 2;
                    }
                    _PackageDetailRepository.UpdEntityList(AllPack);
                    receivingBills.EndDate = DateTime.Now;
                    receivingBillDetails.Status = 1;
                    _receivingBillRepository.UpdEntity(receivingBills);
                }
                else
                {
                    reresult = AddReceivingOrderDetail(receivingBillDetails,  receivedQty, m.NowUserId, m.NowUserName, palletBarcode, out message);
                    if (!reresult)
                    {
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    receivingBills.Status = 1;
                    var AllPack = _PackageDetailRepository.GetEntityAlls().Where(d => d.OrderSn == receivingBills.BillNo).ToList();
                    foreach (var item in AllPack)
                    {
                        item.Status = 1;
                    }
                    _PackageDetailRepository.UpdEntityList(AllPack);
                    _receivingBillRepository.UpdEntity(receivingBills);
                }
                if (_unitOfWork.SaveChangesEntity())
                {
                    StartInventoryDTO startInventoryDTO = new StartInventoryDTO();
                    startInventoryDTO.PalletCode = palletBarcode;
                    startInventoryDTO.ParentPalletCode = m.ParentPalletBarcode;
                    startInventoryDTO.ActualLocation = message;
                    startInventoryDTO.AreaId = aaid;
                    startInventoryDTO.AgvStartCode =m.AgvStartCode;
                    startInventoryDTO.Capsule = m.IsCreatedChecklist == true ? 1 : 0;
                    startInventoryDTO.StockCode=m.StockCode;
                    startInventoryDTO.NowUserId = m.NowUserId;
                    startInventoryDTO.NowUserName = m.NowUserName;
                    reresult = StartReceivingOrderDetails(startInventoryDTO, out message);
                    if (reresult)
                    {
                        message = startInventoryDTO.ActualLocation;
                        _unitOfWork.CommitChanges();



                        return true;
                    }
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }

        #region 机械爪
        //public bool StartMachine(MachineDto m, out string message)
        //{
        //    bool result = false;
        //    bool ishttpok = true;
        //    message = string.Empty;
        //    var robj = _receivingBillRepository.QueryEntityById(m.Id);
        //    if (robj == null)
        //    {
        //        message = "找不到收货单！";
        //        return false;
        //    }
        //    _unitOfWork.BeginTransaction();
        //    try
        //    {
        //        if (robj.Status == 2)
        //        {
        //            _unitOfWork.RollbackChanges();
        //            message = "该单据已完成；";
        //            return false;
        //        }

        //        robj.Status = 1;
        //        #region wcs
        //        if (Config.IsDev == false)
        //        {
        //            ReceivingBillOrderDto receivingBillOrderDto = new ReceivingBillOrderDto();
        //            receivingBillOrderDto.Id = robj.Id;
        //            var wcsresult2 = _wcsHttpClient.StartMachineTaskApi(receivingBillOrderDto);
        //            if (wcsresult2.Code != EmApiResCode.Success)
        //            {
        //                message = wcsresult2.Msg;
        //                result = false;
        //                ishttpok = false;
        //            }
        //            else
        //            {
        //                InterfaceLog interfaceLog = new InterfaceLog();
        //                interfaceLog.Name = "StartMachine";
        //                interfaceLog.Url = "ReceivingOrderDetail/StartMachine";
        //                interfaceLog.CallWay = 2;
        //                interfaceLog.CallWayStr = "POST";
        //                interfaceLog.InParam = JsonConvert.SerializeObject(m);
        //                interfaceLog.OutParam = wcsresult2.ReturnInfo;
        //                interfaceLog.ExecDate = DateTime.Now;
        //                interfaceLog.FinishedDate = DateTime.Now;
        //                interfaceLog.Status = 1;
        //                _interfaceLogRepository.AddEntity(interfaceLog);
        //            }
        //        }
        //        #endregion
        //        result = _unitOfWork.SaveChangesEntity();
        //        if (!ishttpok)
        //        {
        //            _unitOfWork.RollbackChanges();
        //            InterfaceLog interfaceLog = new InterfaceLog();
        //            interfaceLog.Name = "StartMachine";
        //            interfaceLog.Url = "ReceivingOrderDetail/StartMachine";
        //            interfaceLog.CallWay = 2;
        //            interfaceLog.CallWayStr = "POST";
        //            interfaceLog.InParam = JsonConvert.SerializeObject(m);
        //            interfaceLog.OutParam = message;
        //            interfaceLog.ExecDate = DateTime.Now;
        //            interfaceLog.FinishedDate = DateTime.Now;
        //            interfaceLog.Status = 3;
        //            _interfaceLogRepository.AddEntity(interfaceLog);
        //            _unitOfWork.SaveChangesEntity();
        //            return false;
        //        }
        //        _unitOfWork.CommitChanges();
        //        return true;
        //    }
        //    catch (Exception)
        //    {
        //        _unitOfWork.RollbackChanges();
        //        throw;
        //    }
        //}

        public bool GetEmptyPalletBarcode(string palletbarcode, decimal qty, out string message)
        {
            //生成入库任务
            message = string.Empty;
            decimal receivedQty = 0;
            //查询托盘
            var pallobj = _palletRepository.QueryEntityWhere(x => x.PalletBarcode == palletbarcode && x.Status == 1);
            if (pallobj == null)
            {
                message = "该托盘不存在或已被禁用";
                return false;
            }
            //查询库存是否存在该托盘
            var inventory = _inventoryRepository.QueryEntityWhere(it => it.PalletBarcode == palletbarcode);
            if (inventory != null)
            {
                message = $"当前托盘{palletbarcode}已在库存中";
                return false;
            }
            _unitOfWork.BeginTransaction();
            try
            {
                ReceivingBill receivingBill = new ReceivingBill();
                receivingBill.BillNo = "R" + DateTime.Now.ToString("yyyyMMddHHmmss");
                receivingBill.Status = 2;
                receivingBill.TotalQty = qty;
                receivingBill.EndDate = DateTime.Now;
                receivingBill.WarehouseId = 551430736916485;
                receivingBill.WarehouseCode = "1";
                receivingBill.WarehouseName = "库房";
                receivingBill.BillType = 11;
                receivingBill.CreateUserName = "系统";
                _receivingBillRepository.AddEntity(receivingBill);
                if (!_unitOfWork.SaveChangesEntity())
                {
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                ReceivingBillDetail receivingBillDetail = new ReceivingBillDetail();
                receivingBillDetail.BillId = receivingBill.Id;
                receivingBillDetail.BillNo = receivingBill.BillNo;
                receivingBillDetail.MaterialId = 609393181765637;
                receivingBillDetail.MaterialCode = "Pallet";
                receivingBillDetail.MaterialName = "空托盘";
                receivingBillDetail.MaterialTypeName = "空托盘";
                receivingBillDetail.Qty = qty;
                receivingBillDetail.ReceivedQty = qty;
                receivingBillDetail.Status = 1;
                receivingBillDetail.CreateUserName = "系统";
                receivingBillDetail.AreaId = 552864758185989;
                _receivingBillDetailRepository.AddEntity(receivingBillDetail);
                if (!_unitOfWork.SaveChangesEntity())
                {
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                receivedQty = qty;

                bool reresult = false;
                //全部收货完成
                reresult = AddReceivingOrderDetail(receivingBillDetail, receivedQty, 0, "机械爪", palletbarcode, out message);
                if (!reresult)
                {
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                StartInventoryDTO startInventoryDTO = new StartInventoryDTO();
                startInventoryDTO.PalletCode = palletbarcode;
                startInventoryDTO.ActualLocation = message;
                startInventoryDTO.NowUserId = 0;
                startInventoryDTO.NowUserName = "机械爪";
                reresult = StartReceivingOrderDetails(startInventoryDTO, out message);
                if (reresult)
                {
                    message = startInventoryDTO.PalletCode;
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }

        public bool FinishMachine(MachineDto m, out string message)
        {
            message = string.Empty;
            var robj = _receivingBillRepository.QueryEntityById(m.Id);
            if (robj == null)
            {
                message = "找不到收货单！";
                return false;
            }
            if (robj.Status == 0)
            {
                message = "只有进行中的任务才可以结束！";
                return false;
            }
            robj.Status = 2;
            robj.EndDate = DateTime.Now;
            var rdobj = _receivingBillDetailRepository.QueryEntityWhere(x => x.BillId == robj.Id);
            if (rdobj == null)
            {
                message = "找不到收货单明细！";
                return false;
            }
            robj.TotalQty = rdobj.ReceivedQty;
            rdobj.Qty = rdobj.ReceivedQty;
            rdobj.Status = 1;
            return _unitOfWork.SaveChangesEntity();
        }
        #endregion

        #region PDA
        /// <summary>
        /// 弃用开始入库，和收货入库合并成一步
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool StartReceivingOrderDetail(StartInventoryDTO m, out string message)
        {
            message = string.Empty;
            var stackingstoragelist = _stackingStorageRepository.GetEntityWhereAll(x => x.PalletBarcode == m.PalletCode).ToList();
            if (!stackingstoragelist.Any())
            {
                message = "找不到组垛信息";
                return false;
            }
            bool result = false;
            _unitOfWork.BeginTransaction();
            try
            {
                foreach (var item in stackingstoragelist)
                {
                    if (item.RelatedOrderDetailId == null || item.RelatedOrderDetailId < -0)
                    {
                        message = "入库信息有误！";
                        return false;
                    }
                    var reorderDetail = _receivingOrderDetailRepository.QueryEntityById((long)item.RelatedOrderDetailId); ;
                    if (reorderDetail == null)
                    {
                        message = "入库信息有误！";
                        return false;
                    }
                    if (reorderDetail.Status == 2)
                    {
                        message = "当前入库单正在作业中！";
                        return false;
                    }
                    if (reorderDetail.Status == 3)
                    {
                        message = "当前入库单已完成！";
                        return false;
                    }
                    var pallobj = _palletRepository.QueryEntityWhere(x => x.PalletBarcode == item.PalletBarcode);
                    if (pallobj == null || pallobj.Status == 0)
                    {
                        message = "该托盘已被禁用";
                        return false;
                    }
                    item.ActualLocation = m.ActualLocation;
                    _stackingStorageRepository.UpdEntity(item);
                    //组垛id
                    long? stackingStorageId = item.Id;
                    if (stackingStorageId == null || stackingStorageId <= 0)
                    {
                        message = "组垛信息有误！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    reorderDetail.Status = 2;
                    //添加指令
                    Instruct instruct = new Instruct
                    {
                        Status = 2,
                        WarehouseCode = reorderDetail.WarehouseCode,
                        ToLocation = m.ActualLocation,
                        StackingStorageId = stackingStorageId,
                        WorkDeviceType = 1,
                        InstructType = 1,
                        Action = 0,
                        RelatedOrderId = reorderDetail.Id,
                        DeviceCode = "",
                        ExpectedToLocation = m.ActualLocation,
                        InstructIndex = 1,
                        PalletBarcode = m.PalletCode,
                        Priority = 9999,
                        Qty = (decimal)reorderDetail.StackedQty,
                        BusinessType = (int)EmBusinessType.In,
                        CreateUserId = m.NowUserId,
                        CreateUserName = m.NowUserName,
                    };
                    _instructRepository.AddEntity(instruct);
                    var allocateCell = _cellRepository.QueryEntityWhere(x => x.Code == m.ActualLocation);
                    if (allocateCell == null)
                    {
                        message = "仓位信息有误！";
                        return false;
                    }
                    pallobj.LocationCode = allocateCell.Code;
                    pallobj.LocationName = allocateCell.Name;
                    _palletRepository.UpdEntity(pallobj);
                    //保存库存
                    Inventory inventory = new Inventory()
                    {
                        WarehouseId = allocateCell.WhId,
                        WarehouseCode = allocateCell.WhCode,
                        WarehouseName = allocateCell.WhName,
                        AreaCode = allocateCell.AreaCode,
                        AreaName = allocateCell.AreaName,
                        AreaId = allocateCell.AreaId,
                        LocationId = allocateCell.Id,
                        LocationCode = allocateCell.Code,
                        LocationDepth = allocateCell.DepthIndex,
                        LocationName = allocateCell.Name,
                        Status = 3,
                        PalletBarcode = m.PalletCode,
                        ParentPalletBarcode = item.PalletBarcode,
                        RelatedOrderDetailId = reorderDetail.Id,
                        BillType = (int)reorderDetail.BillType.GetValueOrDefault(),
                        IsLock = true,
                        MaterialId = reorderDetail.MaterialId,
                        MaterialCode = reorderDetail.MaterialCode,
                        MaterialName = reorderDetail.MaterialName,
                        CustomerId = reorderDetail.CustomerId,
                        CustomerName = reorderDetail.CustomerName,
                        SupplierId = reorderDetail.SupplierId,
                        SupplierName = reorderDetail.SupplierName,
                        HasSkuDetail = true,
                        PutawayQty = reorderDetail.Qty,
                        UnitId = reorderDetail.UnitId,
                        UnitName = reorderDetail.UnitName,
                        MaterialKeyId = reorderDetail.MaterialKeyId,
                        BatchNo = reorderDetail.BatchNo,
                        ExpireDate = reorderDetail.ExpireDate,
                        ProductDate = reorderDetail.ProductDate,
                        MaterialTypeCode = reorderDetail.MaterialTypeCode,
                        MaterialTypeName = reorderDetail.MaterialTypeName,
                        PickedQty = 0,
                        ErplocationCode = allocateCell.Erpcode,
                        RoutewayId = allocateCell.RoutewayId,
                        StackingStorageId = stackingStorageId,
                        LocationHeightType = allocateCell.HeightType,
                        LogicalPartCode = reorderDetail.LogicalPartCode,//按单据来
                        LocationColumnNo = allocateCell.ColumnNo,
                        LocationLayerNo = allocateCell.LayerNo,
                        LocationDistanceValue = Convert.ToInt32(allocateCell.IsMaxDepth),
                        LocationLineNo = allocateCell.LineNo,
                        AvailableQty = reorderDetail.ReceivedQty,
                        AllocateQty = 0,
                        CreateUserId = m.NowUserId,
                        CreateUserName = m.NowUserName,
                    };
                    _inventoryRepository.AddEntity(inventory);
                    if (!_unitOfWork.SaveChangesEntity())
                    {
                        message = "保存库存失败！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    //库存明细保存
                    InventoryDetail inventoryDetail = new InventoryDetail()
                    {
                        Id = YitIdHelper.NextId(),
                        InventoryId = inventory.Id,
                        PalletBarcode = m.PalletCode,
                        SkuNum = reorderDetail.Qty,
                        IsSku = false,
                    };
                    _inventoryDetailRepository.AddEntity(inventoryDetail);
                    //保存上架单主表
                    string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string putawayCode = "PUT" + str;
                    PutawayOrder putawayOrder = new PutawayOrder();
                    putawayOrder.Id = YitIdHelper.NextId();
                    putawayOrder.Code = putawayCode;
                    putawayOrder.BillType = 1;
                    putawayOrder.RelatedOrderDetailId = reorderDetail.Id;
                    putawayOrder.StackingStorageId = (long)stackingStorageId;
                    putawayOrder.PalletBarcode = m.PalletCode;
                    putawayOrder.LocationCode = allocateCell.Code;
                    putawayOrder.LocationDepth = allocateCell.DepthIndex == 0 ? null : allocateCell.DepthIndex;
                    putawayOrder.Status = 4;
                    putawayOrder.Qty = reorderDetail.ReceivedQty;
                    putawayOrder.MaterialId = reorderDetail.MaterialId;
                    putawayOrder.MaterialCode = reorderDetail.MaterialCode;
                    putawayOrder.MaterialName = reorderDetail.MaterialName;
                    putawayOrder.MaterialKeyId = reorderDetail.MaterialKeyId;
                    putawayOrder.SourceType = 1;
                    putawayOrder.Roadway = allocateCell.RoutewayId.ToString();
                    putawayOrder.CreateUserName = m.NowUserName;

                    _putawayOrderRepository.AddEntity(putawayOrder);
                    result = _unitOfWork.SaveChangesEntity();
                    if (!result)
                    {
                        message = "保存库存失败！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    //上架单明细表保存
                    PutawayOrderDetail putawayOrderDetail = new PutawayOrderDetail()
                    {
                        Id = YitIdHelper.NextId(),
                        PutawayOrderId = putawayOrder.Id,
                        PalletBarcode = m.PalletCode,
                    };
                    _putawayOrderDetailRepository.AddEntity(putawayOrderDetail);
                    if (allocateCell.AreaCode.Contains('P'))
                        result = StaticFinishReceivingOrderDetail(putawayCode, out message);
                }
                if (result)
                {
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }
        private bool StartReceivingOrderDetails(StartInventoryDTO m, out string message)
        {
            message = string.Empty;
            bool Kpallent = false;
            var IsNullPallet = "";
            if (m.PalletCode == "0")
            {
                IsNullPallet = "0";
            }
            IsNullPallet = m.PalletCode;
             var stackingstoragelist = _stackingStorageRepository.GetEntityWhereAll(x => x.PalletBarcode == m.PalletCode &&x.ExpectedLocation==m.ActualLocation  && x.Status == 1).ToList();
            if (!stackingstoragelist.Any())
            {
                message = "找不到组垛信息";
                return false;
            }
            bool result = false;
            foreach (var item in stackingstoragelist)
            {
                if (item.RelatedOrderDetailId == null || item.RelatedOrderDetailId < -0)
                {
                    message = "入库信息有误！";
                    return false;
                }
                var reorderDetail = _receivingOrderDetailRepository.QueryEntityById((long)item.RelatedOrderDetailId);
                var material = _materialRepository.QueryEntityWhere(d => d.Id == item.MaterialId);
                
                if (reorderDetail == null)
                {
                    message = "入库信息有误！";
                    return false;
                }
                if (reorderDetail.Status == 2)
                {
                    message = "当前入库单正在作业中！";
                    return false;
                }
                if (material.Name == "空托盘")
                {
                    Kpallent = true;
                }
                if (reorderDetail.Status == 3)
                {
                    message = "当前入库单已完成！";
                    return false;
                }
                var area = _areaRepository.QueryEntityWhere(d => d.Id == m.AreaId);

                var pallobj = _palletRepository.QueryEntityWhere(x => x.PalletBarcode == item.PalletBarcode);
                if (area.Code.Contains("L"))
                {
                    if (pallobj == null || pallobj.Status == 0)
                    {
                        message = "该托盘已被禁用";
                        return false;
                    }
                }
               
                item.Status = 0;
                item.ActualLocation = m.ActualLocation;
                _stackingStorageRepository.UpdEntity(item);
                //组垛id
                long? stackingStorageId = item.Id;
                if (stackingStorageId == null || stackingStorageId <= 0)
                {
                    message = "组垛信息有误！";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                reorderDetail.Status = 2;
                //添加指令
                 Instruct instruct = new Instruct
                {
                    Status = 2,
                    WarehouseCode = reorderDetail.WarehouseCode,
                    ToLocation = m.ActualLocation,
                    StackingStorageId = stackingStorageId,
                    WorkDeviceType = 1,
                    InstructType = 1,
                    Action = 0,
                    RelatedOrderId = reorderDetail.Id,
                    DeviceCode = "",
                    ExpectedToLocation = m.ActualLocation,
                    InstructIndex = 1,
                    PalletBarcode = m.PalletCode,
                    Priority = 9999,
                    Qty = (decimal)reorderDetail.StackedQty,
                    BusinessType = (int)EmBusinessType.In,
                    CreateUserId = m.NowUserId,
                    CreateUserName = m.NowUserName,
                };
                _instructRepository.AddEntity(instruct);
                var allocateCell = _cellRepository.QueryEntityWhere(x => x.Code == m.ActualLocation && x.AreaId==m.AreaId);
                if (allocateCell == null)
                {
                    message = "仓位信息有误！";
                    return false;
                }
                if (area.Code.Contains("L"))
                {
                    pallobj.LocationCode = allocateCell.Code;
                    pallobj.LocationName = allocateCell.Name;
                }
               
                
                var stockCode = string.Empty;
                var stockName = string.Empty;
                
                if (!string.IsNullOrEmpty(m.StockCode))
                {
                    var stockcode = stockRepository.QueryEntityWhere(d => d.StockCode == m.StockCode);
                    stockCode = stockcode.StockCode;
                    stockName= stockcode.StockName;
                }
                else
                {
                    stockCode = null;
                    stockName = null;
                }

                if (area.Code.Contains("L"))
                {
                    _palletRepository.UpdEntity(pallobj);
                }
           
                //保存库存
                Inventory inventory = new Inventory()
                {
                    WarehouseId = allocateCell.WhId,
                    WarehouseCode = allocateCell.WhCode,
                    WarehouseName = allocateCell.WhName,
                    //备注 为erp所属stock仓库名称
                    StockCode= stockCode,
                    StockName= stockName,
                    Remark = allocateCell.Remark,
                    AreaCode = allocateCell.AreaCode,
                    AreaName = allocateCell.AreaName,
                    AgvStartCode=m.AgvStartCode,
                    Capsule=m.Capsule,
                    AreaId = allocateCell.AreaId,
                    LocationId = allocateCell.Id,
                    LocationCode = allocateCell.Code,
                    LocationDepth = allocateCell.DepthIndex,
                    LocationName = allocateCell.Name,
                    Status = 3,
                    PalletBarcode = IsNullPallet,
                    ParentPalletBarcode = m.ParentPalletCode,
                    RelatedOrderDetailId = reorderDetail.Id,
                    BillType = (int)reorderDetail.BillType.GetValueOrDefault(),
                    IsLock = true,
                    MaterialId = reorderDetail.MaterialId,
                    MaterialCode = reorderDetail.MaterialCode,
                    MaterialName = reorderDetail.MaterialName,
                    CustomerId = reorderDetail.CustomerId,
                    CustomerName = reorderDetail.CustomerName,
                    SupplierId = reorderDetail.SupplierId,
                    SupplierName = reorderDetail.SupplierName,
                    HasSkuDetail = true,
                    PutawayQty = reorderDetail.Qty,
                    UnitId = reorderDetail.UnitId,
                    UnitName = reorderDetail.UnitName,
                    MaterialKeyId = reorderDetail.MaterialKeyId,
                    BatchNo = reorderDetail.BatchNo,
                    ExpireDate = reorderDetail.ExpireDate,
                    ProductDate = reorderDetail.ProductDate,
                    MaterialTypeCode = reorderDetail.MaterialTypeCode,
                    MaterialTypeName = reorderDetail.MaterialTypeName,
                    PickedQty = 0,
                    MaterialCategoryName= material.ModelSpec,
                    ErplocationCode = allocateCell.Erpcode,
                    RoutewayId = allocateCell.RoutewayId,
                    StackingStorageId = stackingStorageId,
                    LocationHeightType = allocateCell.HeightType,
                    LogicalPartCode = reorderDetail.LogicalPartCode,//按单据来
                    LocationColumnNo = allocateCell.ColumnNo,
                    LocationLayerNo = allocateCell.LayerNo,
                    LocationDistanceValue = Convert.ToInt32(allocateCell.IsMaxDepth),
                    LocationLineNo = allocateCell.LineNo,
                    AvailableQty = reorderDetail.ReceivedQty,
                    AllocateQty = 0,
                    CreateUserId = m.NowUserId,
                    CreateUserName = m.NowUserName,
                };
                _inventoryRepository.AddEntity(inventory);
                if (!_unitOfWork.SaveChangesEntity())
                {
                    message = "保存库存失败！";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                //库存明细保存
                InventoryDetail inventoryDetail = new InventoryDetail()
                {
                    Id = YitIdHelper.NextId(),
                    InventoryId = inventory.Id,
                    PalletBarcode = m.PalletCode,
                    SkuNum = reorderDetail.Qty,
                    IsSku = false,
                };
                _inventoryDetailRepository.AddEntity(inventoryDetail);
                //保存上架单主表
                string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string putawayCode = "PUT" + str;
                PutawayOrder putawayOrder = new PutawayOrder();
                putawayOrder.Id = YitIdHelper.NextId();
                putawayOrder.Code = putawayCode;
                putawayOrder.BillType = 1;
                putawayOrder.CreateDate = DateTime.Now;
                putawayOrder.RelatedOrderDetailId = reorderDetail.Id;
                putawayOrder.StackingStorageId = (long)stackingStorageId;
                putawayOrder.PalletBarcode = m.PalletCode;
                putawayOrder.LocationCode = allocateCell.Code;
                putawayOrder.LocationDepth = allocateCell.DepthIndex == 0 ? null : allocateCell.DepthIndex;
                putawayOrder.Status = 4;
                putawayOrder.Qty = reorderDetail.ReceivedQty;
                putawayOrder.MaterialId = reorderDetail.MaterialId;
                putawayOrder.MaterialCode = reorderDetail.MaterialCode;
                putawayOrder.MaterialName = reorderDetail.MaterialName;
                putawayOrder.MaterialKeyId = reorderDetail.MaterialKeyId;
                putawayOrder.SourceType = 1;
                putawayOrder.Roadway = allocateCell.RoutewayId.ToString();
                putawayOrder.CreateUserName = m.NowUserName;

                _putawayOrderRepository.AddEntity(putawayOrder);
                result = _unitOfWork.SaveChangesEntity();
                if (!result)
                {
                    message = "保存库存失败！";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                //上架单明细表保存
                PutawayOrderDetail putawayOrderDetail = new PutawayOrderDetail()
                {
                    Id = YitIdHelper.NextId(),
                    PutawayOrderId = putawayOrder.Id,
                    PalletBarcode = m.PalletCode,
                };
                _putawayOrderDetailRepository.AddEntity(putawayOrderDetail);

                if (allocateCell.AreaCode.Contains('P'))
                {
                    result = StaticFinishReceivingOrderDetail(putawayCode, out message);
                }

                //WMS给WCS下发入库任务
                if (!Config.IsDev)
                {
                    if (!Kpallent)
                    {
                        WcsTaskDto wcsTaskDtoRK = new WcsTaskDto
                        {
                            TaskCode = putawayOrder.Code,
                            TaskType = 1,
                            CellCode = allocateCell.Erpcode,
                            AgvStartCode = m.AgvStartCode,
                            Capsule = m.Capsule,
                            StackCode = m.PalletCode
                        };
                        WcsTaskResultDto? wcsresult2 = _wcsHttpClient.OutTaskApi(wcsTaskDtoRK);
                        if (wcsresult2.Code != EmApiResCode.Success)
                        {
                            message = wcsresult2.Msg;
                            result = false;
                            _unitOfWork.RollbackChanges();
                            break;
                        }
                        else
                        {

                            InterfaceLog interfaceLog = new InterfaceLog();
                            interfaceLog.Name = "SendTask";
                            interfaceLog.Url = "wcs/ExternalApi/SendTask";
                            interfaceLog.CallWay = 2;
                            interfaceLog.CallWayStr = "POST";
                            interfaceLog.InParam = JsonConvert.SerializeObject(m);
                            interfaceLog.OutParam = wcsresult2.Msg + $"(入库)托盘{inventory.PalletBarcode} 仓位{inventory.LocationCode}";
                            interfaceLog.ExecDate = DateTime.Now;
                            interfaceLog.FinishedDate = DateTime.Now;
                            interfaceLog.Status = 1;
                            _interfaceLogRepository.AddEntity(interfaceLog);
                            _unitOfWork.SaveChangesEntity();
                        }
                    }
                }
                   
            }
            if (result)
            {
                
                return true;
            }
            _unitOfWork.RollbackChanges();
            return false;

        }
        public StackingReceivingsDto? GetReceivingRoderData(string PalletCode, out string message)
        {
            message = string.Empty;
            var stackingStoragelist = _stackingStorageRepository.GetEntityWhereAll(s => s.Status == 1 && s.PalletBarcode == PalletCode);

            if (!stackingStoragelist.Any())
            {
                message = "无组垛信息！";
                return null;
            }
            var invobj = _inventoryRepository.QueryIsEntityWhere(x => x.PalletBarcode == PalletCode);
            if (invobj != null)
            {
                message = "该托盘正在作业中";
                return null;
            }
            StackingReceivingsDto srmodel = new StackingReceivingsDto();
            srmodel.PallteCode = PalletCode;
            foreach (var item in stackingStoragelist)
            {
                if (item.RelatedOrderDetailId == null)
                {
                    message = "组垛入库关联id有误！";
                    return null;
                }
                srmodel.Cell = item.ExpectedLocation;

                MaterNum maternum = new MaterNum();
                maternum.MaterialCode = item.MaterialCode;
                maternum.Num = item.Qty;
                srmodel.materNum.Add(maternum);
            }

            //var orderDetail = _receivingOrderDetailRepository.QueryEntityById((long)stackingStorageobj.RelatedOrderDetailId);
            //if (orderDetail == null)
            //{
            //    message = "入库单查询失败";
            //    return null;
            //}


            return srmodel;
        }
        public  bool FinishReceivingOrderDetail(string putcode, out string message)
        {
            _unitOfWork.BeginTransaction();
            try
            {
                 var result = StaticFinishReceivingOrderDetail(putcode, out message);
                if (result)
                {
                    _unitOfWork.CommitChanges();
                    return true;
                }
                
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
               
                throw;
            }

        }

        /// <summary>
        /// 完成入库
        /// </summary>
        /// <param name="putcode"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool StaticFinishReceivingOrderDetail(string putcode, out string message)
        {
            bool IsNullPallent = false;
            message = string.Empty;
            var putobj = _putawayOrderRepository.QueryEntityWhere(x => x.Code == putcode && x.SourceType == 1 && x.Status == 4);
            var eceivingOrderDetail = _receivingOrderDetailRepository.QueryEntityWhere(d => d.Id == putobj.RelatedOrderDetailId);
            if (putobj == null)
            {
                message = "找不到上架单！";
                return false;
            }
            string? pallbarcode = putobj.PalletBarcode;
            if (eceivingOrderDetail.AreaCode.Contains("L"))
            {
                if (string.IsNullOrEmpty(pallbarcode))
                {
                    message = "托盘信息有误！";
                    return false;
                }
            }
           
            var instructlist = _instructRepository.GetEntityWhereAll(x => x.PalletBarcode == pallbarcode && x.Status == 2 && x.InstructType == 1).ToList();
            if (!instructlist.Any())
            {
                message = "未查询到指令！"; 
                _unitOfWork.RollbackChanges();
                return false;
            }
            foreach (var instruct in instructlist)
            {
                if (instruct.PalletBarcode == "0")
                {
                    IsNullPallent = false;
                }
                else
                {
                    IsNullPallent = true;
                }
                if (eceivingOrderDetail.AreaCode.Contains("L"))
                {
                    if (string.IsNullOrEmpty(instruct.PalletBarcode))
                    {
                        message = "参数错误";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                }
                    
                if (instruct.RelatedOrderId == null)
                {
                    message = "关联的入库单id信息有误！";
                    return false;
                }
                var orderDetail = _receivingOrderDetailRepository.QueryEntityById((long)instruct.RelatedOrderId);
                if (orderDetail == null)
                {
                    message = "入库单明细不存在";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                var inventory = _inventoryRepository.QueryEntityWhere(x => x.PalletBarcode == instruct.PalletBarcode && x.IsLock == true && x.RelatedOrderDetailId == (long)instruct.RelatedOrderId);
                if (inventory == null)
                {
                    message = "库存数据不存在";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                var cell = _cellRepository.QueryEntityWhere(x => x.Code == instruct.ExpectedToLocation);
                if (cell == null)
                {
                    message = "仓位数据不存在";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                DateTime? now = DateTime.Now;
                instruct.Status = 4;
                instruct.EndTime = now;
                _instructRepository.UpdEntity(instruct);
                inventory.Status = 1;
                inventory.AllocateQty = 0;
                inventory.InStockDate = now;
                inventory.PutawayQty = instruct.Qty;
                inventory.IsLock = false;
                _inventoryRepository.UpdEntity(inventory);
                orderDetail.ReceivedQty = instruct.Qty;
                orderDetail.InStarDate = now;
                orderDetail.Status = 3;
                _receivingOrderDetailRepository.UpdEntity(orderDetail);
                //删除组垛信息
                var stackingstorage = _stackingStorageRepository.QueryEntityById(instruct.StackingStorageId ?? 0);
                if (stackingstorage != null)
                    _stackingStorageRepository.DelEntity(stackingstorage);

                //库存流水
                InventoryLog inventoryLog = new InventoryLog()
                {
                    Id = YitIdHelper.NextId(),
                    SourceType = 0,
                    SourceSn = orderDetail.OrderSn,
                    WarehouseId = orderDetail.WarehouseId,
                    WarehouseName = orderDetail.WarehouseName,
                    AreaName = inventory.AreaName,
                    AreaId = inventory.AreaId,
                    LocationCode = inventory.LocationCode,
                    PalletBarcode = instruct.PalletBarcode,
                    MaterialId = orderDetail.MaterialId,
                    MaterialCode = orderDetail.MaterialCode,
                    MaterialName = orderDetail.MaterialName,
                    BatchNo = orderDetail.BatchNo,
                    StartQty = 0,
                    ChangeQty = instruct.Qty,
                    EndQty = instruct.Qty,
                    BaseUnitId = orderDetail.UnitId,
                    BaseUnitName = orderDetail.UnitName,
                    CreateDate = DateTime.Now,
                };
                _inventoryLogRepository.AddEntity(inventoryLog);
            }
            var putlist = _putawayOrderRepository.GetEntityWhereAll(x => x.SourceType == 1 && x.Status == 4 && x.PalletBarcode == pallbarcode);
            foreach (var item in putlist)
            {
                item.Status = 5;
                item.Fifodate = DateTime.Now;
                _putawayOrderRepository.UpdEntity(item);
            }

            if (_unitOfWork.SaveChangesEntity())
            {
                if (!Config.IsDevErp)
                {

                    if (IsNullPallent)
                    {
                        var putobj2 = _putawayOrderRepository.QueryEntityWhere(x => x.Code == putcode && x.SourceType == 1 && x.Status == 5);
                        var ReceivingOrderDetail = _receivingOrderDetailRepository.QueryEntityWhere(d => d.Id == putobj2.RelatedOrderDetailId);

                        var ReceivingBillDetail = _receivingBillDetailRepository.QueryEntityWhere(d => d.Id == ReceivingOrderDetail.ReceivingBillDetailId);

                        var ReceivingBill = _receivingBillRepository.QueryEntityWhere(d => d.Id == ReceivingBillDetail.BillId);
                        var supplier = string.Empty;
                        if (ReceivingBill.SupplierId != 0)
                        {
                            var supplier1 = _supplierRepository.QueryEntityWhere(d => d.Id == ReceivingBill.SupplierId);
                            supplier = supplier1.Code;
                        }
                        var modelSpec = string.Empty;
                        var UnitName = string.Empty;
                        if (!string.IsNullOrEmpty(putobj2.MaterialCode))
                        {
                            var material = _materialRepository.QueryEntityWhere(d => d.Code == putobj2.MaterialCode);
                            modelSpec = material.ModelSpec;
                            UnitName = material.UnitName;
                        }
                        var stockCode = string.Empty;
                        var stockPlace = string.Empty;
                        if (!string.IsNullOrEmpty(ReceivingBill.StockCode))
                        {
                            var stock = stockRepository.QueryEntityWhere(d => d.StockCode == ReceivingBill.StockCode);
                            stockCode = stock.StockCode;
                            stockPlace = stock.SPGroupCode;
                        }
                        var othertypename = string.Empty;
                        if (!string.IsNullOrEmpty(ReceivingBill.OtherTypeCode))
                        {
                            var OtherType = _otherTypeRepository.QueryEntityWhere(d => d.TypeCode == ReceivingBill.OtherTypeCode);
                            othertypename = OtherType.TypeName;
                        }

                        //采购和收料通知单
                        if ((ReceivingBill.BillType == 1 || ReceivingBill.BillType == 2) && ReceivingBill.OtherTypeCode == null)
                        {
                            BackERPReceivingBillDTO backreceivingBill = new BackERPReceivingBillDTO
                            {
                                Entry = new List<BackERPReceivingBillDetailListDTO>()
                            };


                            backreceivingBill.BillId = ReceivingOrderDetail.Id;
                            backreceivingBill.BillDate = ReceivingBill.BeginDate.Value.ToString("yyyy-MM-dd");
                            backreceivingBill.SupplierNumber = supplier;
                            backreceivingBill.SupplierName = ReceivingBill.SupplierName;
                            backreceivingBill.POMode = ReceivingBill.POMode;
                            backreceivingBill.BillType = (int)ReceivingBill.BillType;
                            if (ReceivingBill.BillType == 1)
                            {
                                backreceivingBill.SourceType = "采购订单";
                            }
                            if (ReceivingBill.BillType == 2)
                            {
                                backreceivingBill.SourceType = "收料通知";
                            }
                            if (ReceivingBill.BillType == 0)
                            {
                                backreceivingBill.SourceType = "";
                            }
                            backreceivingBill.SourceNo = ReceivingBill.BillNo;

                            BackERPReceivingBillDetailListDTO entry = new BackERPReceivingBillDetailListDTO
                            {
                                Number = ReceivingOrderDetail.MaterialCode,
                                Name = ReceivingOrderDetail.MaterialName,
                                Model = modelSpec,
                                Unit = UnitName,
                                Qty = (decimal)putobj2.Qty,
                                BatchNo = ReceivingOrderDetail.BatchNo,

                                ISPass = ReceivingBillDetail.ISPass,
                                StockNumber = stockCode,
                                StockPlace = putobj2.LocationCode,
                            };
                            backreceivingBill.Entry.Add(entry);



                            string targeUrl = "http://59.110.231.187:9883/api/1";
                            try
                            {
                                var jsonData = JsonConvert.SerializeObject(backreceivingBill);
                                var resultt = _httpClientHelper.PostAsync<WcsTaskResultDto>(
                                    targeUrl,
                                    jsonData,
                                    "application/json"
                                ).Result;

                                if (resultt?.Code != EmApiResCode.Success)
                                {
                                    message = resultt?.Msg ?? "ERP接口调用采购和收料通知单失败";
                                    return false;
                                }
                                resultt.Data = backreceivingBill.BillId;

                                return true;
                            }
                            catch (Exception e)
                            {
                                message = e.Message;
                                return false;
                            }

                        }
                        //产品入库
                        if (ReceivingBill.BillType == 3 && ReceivingBill.OtherTypeCode == null)
                        {
                            BackERPProductionOrderDto ProductionOrderDto = new BackERPProductionOrderDto
                            {
                                Entry = new List<BackERPProductionOrderDetailDto>()
                            };
                            ProductionOrderDto.BillId = ReceivingOrderDetail.Id;
                            ProductionOrderDto.BillDate = ReceivingBill.BeginDate.Value.ToString("yyyy-MM-dd");
                            ProductionOrderDto.DepartmentNumber = ReceivingBill.WorkShopCode;
                            ProductionOrderDto.DepartmentName = ReceivingBill.WorkShopName;
                            ProductionOrderDto.SourceNo = ReceivingBill.BillNo;

                            BackERPProductionOrderDetailDto entry = new BackERPProductionOrderDetailDto
                            {
                                Number = ReceivingOrderDetail.MaterialCode,
                                Name = ReceivingOrderDetail.MaterialName,
                                Model = modelSpec,
                                Unit = UnitName,
                                Qty = (decimal)putobj2.Qty,
                                BatchNo = ReceivingOrderDetail.BatchNo,
                                ISPass = ReceivingBillDetail.ISPass,
                                StockNumber = stockCode,
                                StockPlace = putobj2.LocationCode
                            };
                            ProductionOrderDto.Entry.Add(entry);

                            #region 回传参数
                            string targeUrl = "http://59.110.231.187:9883/api/1";
                            try
                            {
                                var jsonData = JsonConvert.SerializeObject(ProductionOrderDto);
                                var resultt = _httpClientHelper.PostAsync<WcsTaskResultDto>(
                                    targeUrl,
                                    jsonData,
                                    "application/json"
                                ).Result;

                                if (resultt?.Code != EmApiResCode.Success)
                                {
                                    message = resultt?.Msg ?? "ERP接口调用产品入库失败";
                                    return false;
                                }
                                resultt.Data = ProductionOrderDto.BillId;

                                return true;
                            }
                            catch (TaskCanceledException tce) // 捕获超时异常
                            {
                                message = "请求超时，请检查网络连接或稍后重试。";
                                // 如果需要，可以检查 tce.CancellationToken 是否被取消
                                return false;
                            }
                            catch (Exception e)
                            {
                                message = e.Message;
                                return false;
                            }

                            #endregion

                        }
                        //其他入库
                        if (!string.IsNullOrEmpty(ReceivingBill.OtherTypeCode) && ReceivingBill.BillType == 5)
                        {
                            BackERPOtherTypeDto backERPOtherType = new BackERPOtherTypeDto
                            {
                                Entry = new List<BackERPOtherTypeDetailDto>()
                            };
                            backERPOtherType.BillId = ReceivingOrderDetail.Id;
                            backERPOtherType.BillDate = ReceivingBill.BeginDate.Value.ToString("yyyy-MM-dd");
                            backERPOtherType.DepartmentNumber = ReceivingBill.WorkShopCode;

                            backERPOtherType.DepartmentName = ReceivingBill.WorkShopName;
                            backERPOtherType.BillType = othertypename;

                            BackERPOtherTypeDetailDto entry = new BackERPOtherTypeDetailDto
                            {
                                Number = ReceivingOrderDetail.MaterialCode,
                                Name = ReceivingOrderDetail.MaterialName,
                                Model = modelSpec,
                                Unit = UnitName,
                                Qty = (decimal)putobj2.Qty,
                                BatchNo = ReceivingOrderDetail.BatchNo,
                                ISPass = ReceivingBillDetail.ISPass,
                                StockNumber = stockCode,
                                StockPlace = putobj2.LocationCode
                            };
                            backERPOtherType.Entry.Add(entry);



                            #region 回传参数
                            string targeUrl = "http://59.110.231.187:9883/api/1";
                            try
                            {
                                var jsonData = JsonConvert.SerializeObject(backERPOtherType);
                                var resultt = _httpClientHelper.PostAsync<WcsTaskResultDto>(
                                    targeUrl,
                                    jsonData,
                                    "application/json"
                                ).Result;

                                if (resultt?.Code != EmApiResCode.Success)
                                {
                                    message = resultt?.Msg ?? "ERP接口调用其他入库失败";
                                    return false;
                                }
                                resultt.Data = backERPOtherType.BillId;

                                return true;
                            }
                            catch (Exception e)
                            {
                                message = e.Message;
                                return false;
                            }
                            #endregion
                        }
                    }
                   

                }
                return true;
            }


            return false;


        }

        public PickReceivingsDto? GetPickReceivingsInventoryDto(string palletCode, out string message)
        {
            message = string.Empty;
            var pallobj = _palletRepository.QueryEntityWhere(x => x.PalletBarcode == palletCode);
            if (pallobj == null || pallobj.Status == 0)
            {
                message = "托盘不存在或已被禁用！";
                return null;
            }
            var invlist = _inventoryRepository.GetEntityWhereAll(x => x.PalletBarcode == palletCode && x.Status == 1 && x.AreaCode.Contains('P') && x.IsLock == false || (x.PalletBarcode == palletCode && x.Status == 4 && x.AreaCode.Contains('L') && x.IsLock == false));
            PickReceivingsDto pickReceivingsDto = new PickReceivingsDto();
            pickReceivingsDto.PallteCode = palletCode;
            pickReceivingsDto.LoadFactor = pallobj.LoadFactor;
            foreach (var item in invlist)
            {
                pickReceivingsDto.Cell = item.LocationCode;
                PickMaterNum pickmaternum = new PickMaterNum();
                pickmaternum.MaterialCode = item.MaterialCode;
                pickmaternum.MaterialName = item.MaterialName;
                pickmaternum.Batch = item.BatchNo;
                pickmaternum.Arecode = item.AreaCode;
                pickmaternum.InventoryId = item.Id;
                pickmaternum.Num = item.AvailableQty;
                pickReceivingsDto.pickMaterNum.Add(pickmaternum);
            }
            return pickReceivingsDto;
        }

        public bool StartPickReceivingOrderDetail2(PickReceivingsDto m, out string message)
        {
            message = string.Empty;
            decimal? startqty = 0;
            bool result = false;
            var ilist = _inventoryRepository.GetEntityAlls();
            var mlist = _materialRepository.GetEntityAlls();
            var rblist = _receivingBillRepository.GetEntityAlls();
            var rbdlist = _receivingBillDetailRepository.GetEntityAlls();
            var rlist = _receivingOrderDetailRepository.GetEntityAlls();
            var clist = _cellRepository.GetEntityAlls();
            try
            {
                _unitOfWork.BeginTransaction();
                Dictionary<string, int> skeyValuePairs = new Dictionary<string, int>();
                bool IsAdd = true;
                var pobj = _palletRepository.QueryEntityWhere(x => x.PalletBarcode == m.PallteCode);
                if (pobj == null)
                {
                    message = "托盘不存在！";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                if (pobj.Status == 0)
                {
                    message = "托盘已被禁用！";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                pobj.LoadFactor = m.LoadFactor;
                _palletRepository.UpdEntity(pobj);
                var rbdobj = rbdlist.FirstOrDefault(x => x.BillId == m.BillId);
                if (rbdobj == null)
                {
                    message = "找不到收货单明细！";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                var ilists = ilist.Where(x => x.PalletBarcode == pobj.PalletBarcode).ToList();
                foreach (var item in ilists)
                {
                    if (item.MaterialCode == rbdobj.MaterialCode && item.BatchNo == rbdobj.BatchNo)
                    {
                        IsAdd = false;
                        break;
                    }
                }
                #region 呼叫库存中的托盘
                if (!m.pickMaterNum.Any())
                {
                    message = "明细有误！";
                    return false;
                }

                Inventory? inventoryModel = ilist.FirstOrDefault(x => x.Id == m.pickMaterNum.FirstOrDefault().InventoryId);
                //状态修改出库在途         
                if (inventoryModel == null)
                {
                    message = "获取库存信息失败！";
                    return false;
                }
                //inventoryModel.Status = 4;
                var inventorylist = ilist.Where(x => x.PalletBarcode == m.PallteCode && x.Id != inventoryModel.Id && (x.Status == 1 || x.Status == 5));
                if (inventorylist.Any())
                {
                    foreach (var item2 in inventorylist)
                    {
                        item2.IsLock = true;
                        item2.Status = 4;
                        _inventoryRepository.UpdEntity(item2);
                    }
                }
                var cellobj = _cellRepository.QueryEntityWhere(x => x.Code == inventoryModel.LocationCode);
                if (cellobj == null)
                {
                    message = "未查询到仓位" + inventoryModel.LocationCode;
                }

                #region 添加指令
                Instruct inobj = new Instruct();
                inobj.WarehouseCode = inventoryModel.WarehouseCode;
                inobj.Status = 2;
                inobj.ToLocation = inventoryModel.LocationCode;
                inobj.WorkDeviceType = 1;
                inobj.InstructType = 6;
                inobj.Action = 0;
                inobj.RelatedOrderId = 0;
                inobj.ExpectedToLocation = inventoryModel.LocationCode;
                inobj.InstructIndex = 1;
                inobj.PalletBarcode = m.PallteCode;
                inobj.ScanedBarcode = m.PallteCode;
                inobj.Priority = 9999;
                inobj.Qty = 0;
                inobj.FinishedQty = 0;
                inobj.BusinessType = (int)EmBusinessType.Out;
                inobj.RelatedOrderDetailId = 0;
                _instructRepository.AddEntity(inobj);
                #endregion
                #region 添加下架单
                string strr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string pickCode = "ORT" + strr;
                PickingOrder pickOrder = new PickingOrder();
                pickOrder.Id = YitIdHelper.NextId();
                pickOrder.Code = pickCode;
                pickOrder.WarehouseCode = inventoryModel.WarehouseCode;
                pickOrder.WarehouseName = inventoryModel.WarehouseName;
                pickOrder.BillType = 2;
                pickOrder.PalletBarcode = m.PallteCode;
                pickOrder.Roadway = cellobj.RoutewayId.ToString();
                pickOrder.LocationCode = cellobj.Code;
                pickOrder.LocationDepth = cellobj.DepthIndex;
                pickOrder.Status = 4;
                pickOrder.Qty = 0;
                pickOrder.MaterialId = inventoryModel.MaterialId;
                pickOrder.MaterialCode = inventoryModel.MaterialCode;
                pickOrder.MaterialName = inventoryModel.MaterialName;
                pickOrder.MaterialKeyId = inventoryModel.MaterialKeyId;
                pickOrder.BatchNo = inventoryModel.BatchNo;
                pickOrder.SourceType = 2;
                pickOrder.RelatedOrderDetailId = 0;
                pickOrder.CreateDate = DateTime.Now;
                if (inventoryModel.AreaCode.Contains('L'))
                {
                    if (!skeyValuePairs.ContainsKey(m.PallteCode))
                        skeyValuePairs.Add(m.PallteCode, 1);
                    _pickingOrderRepository.AddEntity(pickOrder);
                    PickingOrderDetail pickOrderDetail = new PickingOrderDetail();
                    pickOrderDetail.Id = YitIdHelper.NextId();
                    pickOrderDetail.OrderId = pickOrder.Id;
                    pickOrderDetail.PalletBarcode = m.PallteCode;
                    pickOrderDetail.MaterialBarcode = inventoryModel.MaterialCode;
                    _pickingOrderDetailRepository.AddEntity(pickOrderDetail);
                    #endregion
                }
                #endregion
                //新增物料
                if (IsAdd)
                {
                    _inventoryRepository.DelEntity(inventoryModel);
                    foreach (var item in m.pickMaterNum)
                    {
                        if (item.Qty <= 0 || item.Qty == null)
                        {
                            message = "数量有误！";
                            _unitOfWork.RollbackChanges();
                            result = false;
                        }
                        var rbobj = rblist.FirstOrDefault(x => x.Id == rbdobj.BillId);
                        if (rbobj == null)
                        {
                            message = "收货单有误";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbobj.Status == 2)
                        {
                            message = "收货单已完成";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbdobj.ReceivedQty + item.Qty > rbobj.TotalQty)
                        {
                            message = "已收货数量不能大于总数量！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbdobj.ReceivedQty + item.Qty == rbobj.TotalQty)
                        {
                            rbobj.Status = 2;
                            rbdobj.ReceivedQty += (decimal)item.Qty;
                            _receivingBillRepository.UpdEntity(rbobj);
                            _receivingBillDetailRepository.UpdEntity(rbdobj);
                        }
                        else
                        {
                            rbobj.Status = 1;
                            rbdobj.ReceivedQty += (decimal)item.Qty;
                            _receivingBillRepository.UpdEntity(rbobj);
                            _receivingBillDetailRepository.UpdEntity(rbdobj);
                        }
                        var mobj = mlist.FirstOrDefault(x => x.Id == (long)rbdobj.MaterialId);
                        if (mobj == null)
                        {
                            message = "物料信息有误！";
                            return false;
                        }
                        var maxqty = mobj.MaxSafetyStock;
                        var cobj = clist.FirstOrDefault(x => x.Code == m.Cell);
                        if (cobj == null)
                        {
                            message = "找不到仓位信息！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        ReceivingOrderDetail receivingOrder = new ReceivingOrderDetail();
                        receivingOrder.OrderSn = m.BillNo;
                        //本地入库
                        receivingOrder.BillType = rbobj.BillType;
                        receivingOrder.WarehouseId = rbobj.WarehouseId;
                        receivingOrder.WarehouseCode = rbobj.WarehouseCode;
                        receivingOrder.WarehouseName = rbobj.WarehouseName;
                        receivingOrder.AreaCode = cobj.AreaCode;
                        receivingOrder.AreaName = cobj.AreaName;
                        receivingOrder.SupplierId = rbobj.SupplierId;
                        receivingOrder.SupplierName = rbobj.SupplierName;
                        receivingOrder.CustomerId = rbobj.CustomerId;
                        receivingOrder.CustomerName = rbobj.CustomerName;
                        receivingOrder.MaterialId = rbdobj.MaterialId;
                        receivingOrder.MaterialCode = rbdobj.MaterialCode;
                        receivingOrder.MaterialName = rbdobj.MaterialName;
                        receivingOrder.MaterialTypeCode = rbdobj.MaterialTypeCode;
                        receivingOrder.MaterialTypeName = rbdobj.MaterialTypeName;
                        receivingOrder.UnitId = mobj.UnitId;
                        receivingOrder.UnitName = mobj.UnitName;
                        receivingOrder.BatchNo = rbdobj.BatchNo;
                        //订单来源默认手动创建
                        receivingOrder.SourceType = 2;
                        //质检状态默认为合格
                        receivingOrder.QualityState = 1;
                        //质量状态
                        receivingOrder.Status = 3;
                        receivingOrder.ReceivedQty = item.Qty;
                        receivingOrder.PackagedQty = 0;
                        receivingOrder.PackQty = 0;
                        receivingOrder.BatchNoExplain = rbdobj.BatchNoExplain;
                        receivingOrder.OutFactoryDate = rbdobj.OutFactoryDate;
                        receivingOrder.ProduceFactory = rbdobj.ProduceFactory;
                        receivingOrder.ProductDate = rbdobj.ProductDate;
                        receivingOrder.ExpireDate = rbdobj.ExpireDate;
                        receivingOrder.Qty = item.Qty;
                        receivingOrder.PalletBarcode = m.PallteCode;
                        receivingOrder.ReceivingBillDetailId = rbdobj.Id;
                        receivingOrder.ReceivingBillId = rbobj.Id;
                        #region 审计字段
                        receivingOrder.CreateUserId = m.NowUserId;
                        receivingOrder.CreateUserName = m.NowUserName;
                        #endregion
                        //采购订单行项目类型
                        receivingOrder.PurOrderLineType = 0;
                        receivingOrder.StackedQty = item.Qty;
                        receivingOrder.LocationId = cobj.Id;
                        receivingOrder.LocationCode = cobj.Code;
                        receivingOrder.LocationName = cobj.Name;
                        _receivingOrderDetailRepository.AddEntity(receivingOrder);
                        if (_unitOfWork.SaveChangesEntity() == false)
                        {
                            message = "添加入库单失败!";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        #region 增加库存
                        Inventory inventory = new Inventory();
                        inventory.WarehouseId = cobj.WhId;
                        inventory.WarehouseCode = cobj.WhCode;
                        inventory.WarehouseName = cobj.WhName;
                        inventory.AreaCode = cobj.AreaCode;
                        inventory.AreaName = cobj.AreaName;
                        inventory.AreaId = cobj.AreaId;
                        inventory.LocationId = cobj.Id;
                        inventory.LocationCode = cobj.Code;
                        inventory.LocationDepth = cobj.DepthIndex;
                        inventory.LocationName = cobj.Name;
                        if (inventory.AreaCode.Contains('L'))
                            inventory.Status = 4;
                        else
                            inventory.Status = 1;
                        inventory.PalletBarcode = m.PallteCode;
                        inventory.ParentPalletBarcode = m.PallteCode;
                        inventory.RelatedOrderDetailId = receivingOrder.Id;
                        inventory.BillType = (int)receivingOrder.BillType.GetValueOrDefault();
                        inventory.IsLock = false;
                        inventory.MaterialId = receivingOrder.MaterialId;
                        inventory.MaterialCode = receivingOrder.MaterialCode;
                        inventory.MaterialName = receivingOrder.MaterialName;
                        inventory.CustomerId = receivingOrder.CustomerId;
                        inventory.InStockDate = DateTime.Now;
                        inventory.CustomerName = receivingOrder.CustomerName;
                        inventory.SupplierId = receivingOrder.SupplierId;
                        inventory.SupplierName = receivingOrder.SupplierName;
                        inventory.HasSkuDetail = true;
                        inventory.PutawayQty = receivingOrder.Qty;
                        inventory.UnitId = receivingOrder.UnitId;
                        inventory.UnitName = receivingOrder.UnitName;
                        inventory.MaterialKeyId = receivingOrder.MaterialKeyId;
                        inventory.BatchNo = receivingOrder.BatchNo;
                        inventory.ExpireDate = receivingOrder.ExpireDate;
                        inventory.ProductDate = receivingOrder.ProductDate;
                        inventory.MaterialTypeCode = receivingOrder.MaterialTypeCode;
                        inventory.MaterialTypeName = receivingOrder.MaterialTypeName;
                        inventory.PickedQty = 0;
                        inventory.ErplocationCode = cobj.Erpcode;
                        inventory.RoutewayId = cobj.RoutewayId;
                        inventory.StackingStorageId = 0;
                        inventory.LocationHeightType = cobj.HeightType;
                        inventory.LogicalPartCode = receivingOrder.LogicalPartCode;//按单据来
                        inventory.LocationColumnNo = cobj.ColumnNo;
                        inventory.LocationLayerNo = cobj.LayerNo;
                        inventory.LocationDistanceValue = Convert.ToInt32(cobj.IsMaxDepth);
                        inventory.LocationLineNo = cobj.LineNo;
                        inventory.AvailableQty = receivingOrder.ReceivedQty;
                        inventory.AllocateQty = 0;
                        inventory.CreateUserId = m.NowUserId;
                        inventory.CreateUserName = m.NowUserName;
                        _inventoryRepository.AddEntity(inventory);
                        if (!_unitOfWork.SaveChangesEntity())
                        {
                            message = "保存库存失败！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        //库存明细保存
                        InventoryDetail inventoryDetail = new InventoryDetail()
                        {
                            Id = YitIdHelper.NextId(),
                            InventoryId = inventory.Id,
                            PalletBarcode = m.PallteCode,
                            SkuNum = receivingOrder.Qty,
                            IsSku = false,
                        };
                        _inventoryDetailRepository.AddEntity(inventoryDetail);
                        #endregion
                        if (inventory.AvailableQty > maxqty)
                        {
                            message = "调增后的库存大于该物料最大库存预警！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        startqty = inventory.AvailableQty;
                        //添加指令
                        Instruct instruct = new Instruct
                        {
                            Status = 4,
                            WarehouseCode = inventory.WarehouseCode,
                            ToLocation = inventory.LocationCode,
                            WorkDeviceType = 1,
                            InstructType = 6,
                            Action = 0,
                            RelatedOrderId = inventory.RelatedOrderDetailId,
                            DeviceCode = "",
                            ExpectedToLocation = inventory.LocationCode,
                            InstructIndex = 1,
                            PalletBarcode = inventory.PalletBarcode,
                            Priority = 9999,
                            Qty = (decimal)inventory.AvailableQty,
                            BusinessType = (int)EmBusinessType.In,
                            EndTime = DateTime.Now,
                            ScanedBarcode = inventory.PalletBarcode
                        };
                        _instructRepository.AddEntity(instruct);
                        //保存上架单主表
                        string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        string putawayCode = "RRT" + str;
                        PutawayOrder putawayOrder = new PutawayOrder();
                        putawayOrder.Id = YitIdHelper.NextId();
                        putawayOrder.Code = putawayCode;
                        putawayOrder.BillType = 1;
                        putawayOrder.RelatedOrderDetailId = inventory.Id;
                        putawayOrder.PalletBarcode = inventory.PalletBarcode;
                        putawayOrder.LocationCode = inventory.LocationCode;
                        putawayOrder.LocationDepth = inventory.LocationDepth == 0 ? null : inventory.LocationDepth;
                        putawayOrder.Status = 5;
                        putawayOrder.Qty = inventory.AvailableQty;
                        putawayOrder.MaterialId = inventory.MaterialId;
                        putawayOrder.MaterialCode = inventory.MaterialCode;
                        putawayOrder.MaterialName = inventory.MaterialName;
                        putawayOrder.MaterialKeyId = inventory.MaterialKeyId;
                        putawayOrder.SourceType = 1;
                        putawayOrder.Roadway = inventory.RoutewayId.ToString();

                        _putawayOrderRepository.AddEntity(putawayOrder);
                        if (!_unitOfWork.SaveChangesEntity())
                        {
                            message = "保存库存失败！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        //上架单明细表保存
                        PutawayOrderDetail putawayOrderDetail = new PutawayOrderDetail()
                        {
                            Id = YitIdHelper.NextId(),
                            PutawayOrderId = putawayOrder.Id,
                            PalletBarcode = inventory.PalletBarcode,
                        };
                        _putawayOrderDetailRepository.AddEntity(putawayOrderDetail);
                        //库存流水
                        InventoryLog inventoryLog = new InventoryLog()
                        {
                            Id = YitIdHelper.NextId(),
                            SourceType = 0,
                            SourceSn = receivingOrder.OrderSn,
                            WarehouseId = receivingOrder.WarehouseId,
                            WarehouseName = receivingOrder.WarehouseName,
                            AreaName = inventory.AreaName,
                            AreaId = inventory.AreaId,
                            LocationCode = inventory.LocationCode,
                            PalletBarcode = inventory.PalletBarcode,
                            MaterialId = receivingOrder.MaterialId,
                            MaterialCode = receivingOrder.MaterialCode,
                            MaterialName = receivingOrder.MaterialName,
                            BatchNo = receivingOrder.BatchNo,
                            StartQty = 0,
                            ChangeQty = item.Qty,
                            EndQty = inventory.AvailableQty,
                            BaseUnitId = receivingOrder.UnitId,
                            BaseUnitName = receivingOrder.UnitName,
                            CreateDate = DateTime.Now,
                            Remark = "拣选入库加新物料"
                        };
                        _inventoryLogRepository.AddEntity(inventoryLog);
                    }
                }
                else
                {
                    //库存中已有物料增加数量
                    foreach (var item in m.pickMaterNum)
                    {
                        if (item.Qty <= 0 || item.Qty == null)
                        {
                            message = "数量有误！";
                            result = true;
                        }
                        var rbobj = rblist.FirstOrDefault(x => x.Id == rbdobj.BillId);
                        if (rbobj == null)
                        {
                            message = "收货单有误";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbobj.Status == 2)
                        {
                            message = "收货单已完成";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbdobj.ReceivedQty + item.Qty > rbobj.TotalQty)
                        {
                            message = "已收货数量不能大于总数量！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbdobj.ReceivedQty + item.Qty == rbobj.TotalQty)
                        {
                            rbobj.Status = 2;
                            rbdobj.ReceivedQty += (decimal)item.Qty;
                            _receivingBillRepository.UpdEntity(rbobj);
                            _receivingBillDetailRepository.UpdEntity(rbdobj);
                        }
                        else
                        {
                            rbobj.Status = 1;
                            rbdobj.ReceivedQty += (decimal)item.Qty;
                            _receivingBillRepository.UpdEntity(rbobj);
                            _receivingBillDetailRepository.UpdEntity(rbdobj);
                        }
                        var mobj = mlist.FirstOrDefault(x => x.Id == (long)rbdobj.MaterialId);
                        if (mobj == null)
                        {
                            message = "物料信息有误！";
                            return false;
                        }
                        var maxqty = mobj.MaxSafetyStock;
                        var cobj = clist.FirstOrDefault(x => x.Code == m.Cell);
                        if (cobj == null)
                        {
                            message = "找不到仓位信息！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        ReceivingOrderDetail receivingOrder = new ReceivingOrderDetail();
                        receivingOrder.OrderSn = m.BillNo;
                        //本地入库
                        receivingOrder.BillType = rbobj.BillType;
                        receivingOrder.WarehouseId = rbobj.WarehouseId;
                        receivingOrder.WarehouseCode = rbobj.WarehouseCode;
                        receivingOrder.WarehouseName = rbobj.WarehouseName;
                        receivingOrder.AreaCode = cobj.AreaCode;
                        receivingOrder.AreaName = cobj.AreaName;
                        receivingOrder.SupplierId = rbobj.SupplierId;
                        receivingOrder.SupplierName = rbobj.SupplierName;
                        receivingOrder.CustomerId = rbobj.CustomerId;
                        receivingOrder.CustomerName = rbobj.CustomerName;
                        receivingOrder.MaterialId = rbdobj.MaterialId;
                        receivingOrder.MaterialCode = rbdobj.MaterialCode;
                        receivingOrder.MaterialName = rbdobj.MaterialName;
                        receivingOrder.MaterialTypeCode = rbdobj.MaterialTypeCode;
                        receivingOrder.MaterialTypeName = rbdobj.MaterialTypeName;
                        receivingOrder.UnitId = mobj.UnitId;
                        receivingOrder.UnitName = mobj.UnitName;
                        receivingOrder.BatchNo = rbdobj.BatchNo;
                        //订单来源默认手动创建
                        receivingOrder.SourceType = 2;
                        //质检状态默认为合格
                        receivingOrder.QualityState = 1;
                        //质量状态
                        receivingOrder.Status = 3;
                        receivingOrder.ReceivedQty = item.Qty;
                        receivingOrder.PackagedQty = 0;
                        receivingOrder.PackQty = 0;
                        receivingOrder.BatchNoExplain = rbdobj.BatchNoExplain;
                        receivingOrder.OutFactoryDate = rbdobj.OutFactoryDate;
                        receivingOrder.ProduceFactory = rbdobj.ProduceFactory;
                        receivingOrder.ProductDate = rbdobj.ProductDate;
                        receivingOrder.ExpireDate = rbdobj.ExpireDate;
                        receivingOrder.Qty = item.Qty;
                        receivingOrder.PalletBarcode = m.PallteCode;
                        receivingOrder.ReceivingBillDetailId = rbdobj.Id;
                        receivingOrder.ReceivingBillId = rbobj.Id;
                        #region 审计字段
                        receivingOrder.CreateUserId = m.NowUserId;
                        receivingOrder.CreateUserName = m.NowUserName;
                        #endregion
                        //采购订单行项目类型
                        receivingOrder.PurOrderLineType = 0;
                        receivingOrder.StackedQty = item.Qty;
                        receivingOrder.LocationId = cobj.Id;
                        receivingOrder.LocationCode = cobj.Code;
                        receivingOrder.LocationName = cobj.Name;
                        _receivingOrderDetailRepository.AddEntity(receivingOrder);
                        if (_unitOfWork.SaveChangesEntity() == false)
                        {
                            message = "添加入库单失败!";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        inventoryModel.IsLock = true;
                        inventoryModel.Status = 4;
                        if (inventoryModel.AvailableQty + item.Qty > maxqty)
                        {
                            message = "调增后的库存大于该物料最大库存预警！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        startqty = inventoryModel.AvailableQty;
                        inventoryModel.AvailableQty += item.Qty;
                        _inventoryRepository.UpdEntity(inventoryModel);
                        //出库单单子明细
                        var sllist = _shippingLockCellRepository.GetEntityWhereAll(x => x.InventoryId == inventoryModel.Id && x.Status != 4);
                        foreach (var item2 in sllist)
                        {
                            item2.InventoryQty = inventoryModel.AvailableQty;
                        }
                        //库存流水
                        InventoryLog inventoryLog = new InventoryLog()
                        {
                            Id = YitIdHelper.NextId(),
                            SourceType = 0,
                            SourceSn = receivingOrder.OrderSn,
                            WarehouseId = receivingOrder.WarehouseId,
                            WarehouseName = receivingOrder.WarehouseName,
                            AreaName = inventoryModel.AreaName,
                            AreaId = inventoryModel.AreaId,
                            LocationCode = inventoryModel.LocationCode,
                            PalletBarcode = inventoryModel.PalletBarcode,
                            MaterialId = receivingOrder.MaterialId,
                            MaterialCode = receivingOrder.MaterialCode,
                            MaterialName = receivingOrder.MaterialName,
                            BatchNo = receivingOrder.BatchNo,
                            StartQty = startqty,
                            ChangeQty = item.Qty,
                            EndQty = inventoryModel.AvailableQty,
                            BaseUnitId = receivingOrder.UnitId,
                            BaseUnitName = receivingOrder.UnitName,
                            CreateDate = DateTime.Now,
                            Remark = "拣选入库加数量"
                        };
                        _inventoryLogRepository.AddEntity(inventoryLog);
                        #region 弃用
                        //var invobj = ilist.FirstOrDefault(x => x.Id == item.InventoryId);
                        //if (invobj == null)
                        //{
                        //    message = "找不到库存信息！";
                        //    _unitOfWork.RollbackChanges();
                        //    return false;
                        //}
                        //if (invobj.AvailableQty + item.Qty > maxqty)
                        //{
                        //    message = "调增后的库存大于该物料最大库存预警！";
                        //    _unitOfWork.RollbackChanges();
                        //    return false;
                        //}
                        //startqty = invobj.AvailableQty;
                        //invobj.AvailableQty += item.Qty;
                        //_inventoryRepository.UpdEntity(invobj);
                        ////出库单单子明细
                        //var sllist = _shippingLockCellRepository.GetEntityWhereAll(x => x.InventoryId == invobj.Id && x.IsPicking == false);
                        //foreach (var item2 in sllist)
                        //{
                        //    item2.InventoryQty = invobj.AvailableQty;
                        //}
                        ////库存流水
                        //InventoryLog inventoryLog = new InventoryLog()
                        //{
                        //    Id = YitIdHelper.NextId(),
                        //    SourceType = 0,
                        //    SourceSn = receivingOrder.OrderSn,
                        //    WarehouseId = receivingOrder.WarehouseId,
                        //    WarehouseName = receivingOrder.WarehouseName,
                        //    AreaName = invobj.AreaName,
                        //    AreaId = invobj.AreaId,
                        //    LocationCode = invobj.LocationCode,
                        //    PalletBarcode = invobj.PalletBarcode,
                        //    MaterialId = receivingOrder.MaterialId,
                        //    MaterialCode = receivingOrder.MaterialCode,
                        //    MaterialName = receivingOrder.MaterialName,
                        //    BatchNo = receivingOrder.BatchNo,
                        //    StartQty = startqty,
                        //    ChangeQty = item.Qty,
                        //    EndQty = invobj.AvailableQty,
                        //    BaseUnitId = receivingOrder.UnitId,
                        //    BaseUnitName = receivingOrder.UnitName,
                        //    CreateDate = DateTime.Now,
                        //    Remark = "拣选入库加数量"
                        //};
                        //_inventoryLogRepository.AddEntity(inventoryLog);
                        //if (item.Arecode == "1")
                        //    result = StaticFinishPickReceivingOrderDetail(putawayOrder.Code,out message);
                        #endregion
                    }
                }
                result = _unitOfWork.SaveChangesEntity();
                if (result)
                {
                    if (Config.IsDev == false)
                    {
                        var picklist = _pickingOrderRepository.GetEntityWhereAll(x => x.Status == 4 && x.SourceType == 2);
                        foreach (var item in skeyValuePairs)
                        {
                            var pickobj = picklist.FirstOrDefault(x => x.PalletBarcode == item.Key);
                            if (pickobj == null)
                                continue;
                            WcsTaskDto wcsTaskDto = new WcsTaskDto
                            {
                                TaskCode = pickobj.Code,
                                TaskType = 2,
                                StartPoint = pickobj.LocationCode
                            };
                            var wcsresult = _wcsHttpClient.OutTaskApi(wcsTaskDto);
                            if (wcsresult.ReturnStatus == 1)
                            {
                                message = wcsresult.ReturnInfo;
                                _unitOfWork.RollbackChanges();
                                return false;
                            }
                        }
                    }
                    message = "操作成功！";
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }

        }

        /// <summary>
        /// 支持操作多条单据
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool StartPickReceivingOrderDetail(PickReceivingsDto m, out string message)
        {
            message = string.Empty;
            decimal? startqty = 0;
            bool result = false;
            var ilist = _inventoryRepository.GetEntityAlls();
            var mlist = _materialRepository.GetEntityAlls();
            var rbdlist = _receivingBillDetailRepository.GetEntityAlls();
            var rlist = _receivingOrderDetailRepository.GetEntityAlls();
            var clist = _cellRepository.GetEntityAlls();
            try
            {
                var rbdobj = rbdlist.FirstOrDefault(x => x.BillId == m.BillId);
                if (rbdobj == null)
                {
                    message = "找不到收货单明细！";
                    return false;
                }
                foreach (var item in m.pickMaterNum)
                {
                    _unitOfWork.BeginTransaction();
                    bool IsAdd = true;
                    var pobj = _palletRepository.QueryEntityWhere(x => x.PalletBarcode == item.PalletBarcode);
                    if (pobj == null)
                    {
                        message = "托盘不存在！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (pobj.Status == 0)
                    {
                        message = "托盘已被禁用！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }

                    var ilists = ilist.Where(x => x.PalletBarcode == pobj.PalletBarcode).ToList();
                    foreach (var item2 in ilists)
                    {
                        if (item2.MaterialCode == rbdobj.MaterialCode && item2.BatchNo == rbdobj.BatchNo)
                        {
                            IsAdd = false;
                            break;
                        }
                    }
                    #region 呼叫库存中的托盘
                    Inventory? inventoryModel = ilist.FirstOrDefault(x => x.Id == item.InventoryId);
                    if (inventoryModel == null)
                    {
                        message = "获取库存信息失败！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (inventoryModel.Status != 1 || inventoryModel.IsLock != false)
                    {
                        message = $"托盘{inventoryModel.PalletBarcode}正在作业中！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    #region 如果浅深位有货物产生移库操作
                    if (inventoryModel.AreaCode.Contains('L'))
                    {
                        //排
                        //string rows = inventoryModel.LocationCode.Substring(7, 1);
                        string[] parts12 = inventoryModel.LocationCode.Split('_');
                        string rows = parts12[1];
                        if (string.IsNullOrEmpty(rows))
                        {
                            message = "获取仓位排失败！";
                            return false;
                        }
                        if (rows == "1")
                        {
                            string[] parts = inventoryModel.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_2_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                            {
                                message = $"浅货位 {modifiedcellcode} 已有物资，请先移走在进行操作！";
                                _unitOfWork.RollbackChanges();
                                return false;
                            }
                        }
                        else if (rows == "4")
                        {
                            string[] parts = inventoryModel.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_3_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                            {
                                message = $"浅货位 {modifiedcellcode} 已有物资，请先移走在进行操作！";
                                _unitOfWork.RollbackChanges();
                                return false;
                            }
                        }
                    }
                    #endregion
                    m.Cell = inventoryModel.LocationCode;
                    var inventorylist = ilist.Where(x => x.PalletBarcode == item.PalletBarcode && x.Id != inventoryModel.Id && (x.Status == 1 || x.Status == 5));
                    if (inventorylist.Any())
                    {
                        foreach (var item2 in inventorylist)
                        {
                            item2.IsLock = true;
                            item2.Status = 4;
                            _inventoryRepository.UpdEntity(item2);
                        }
                    }
                    var cellobj = _cellRepository.QueryEntityWhere(x => x.Code == inventoryModel.LocationCode);
                    if (cellobj == null)
                    {
                        message = "未查询到仓位" + inventoryModel.LocationCode;
                        _unitOfWork.RollbackChanges();
                        return false;
                    }

                    #region 添加指令
                    Instruct inobj = new Instruct();
                    inobj.WarehouseCode = inventoryModel.WarehouseCode;
                    if (inventoryModel.AreaCode.Contains("L"))
                        inobj.Status = 2;
                    else
                    {
                        inobj.Status = 4;
                        inobj.EndTime = DateTime.Now;
                    }
                    inobj.ToLocation = inventoryModel.LocationCode;
                    inobj.WorkDeviceType = 1;
                    inobj.InstructType = 6;
                    inobj.Action = 0;
                    inobj.RelatedOrderId = 0;
                    inobj.ExpectedToLocation = inventoryModel.LocationCode;
                    inobj.InstructIndex = 1;
                    inobj.PalletBarcode = item.PalletBarcode;
                    inobj.ScanedBarcode = item.PalletBarcode;
                    inobj.Priority = 9999;
                    inobj.Qty = 0;
                    inobj.FinishedQty = 0;
                    inobj.BusinessType = (int)EmBusinessType.Out;
                    inobj.RelatedOrderDetailId = 0;
                    _instructRepository.AddEntity(inobj);
                    #endregion
                    #region 添加下架单
                    string strr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string pickCode = "ORT" + strr;
                    PickingOrder pickOrder = new PickingOrder();
                    pickOrder.Id = YitIdHelper.NextId();
                    pickOrder.Code = pickCode;
                    pickOrder.WarehouseCode = inventoryModel.WarehouseCode;
                    pickOrder.WarehouseName = inventoryModel.WarehouseName;
                    pickOrder.BillType = 2;
                    pickOrder.PalletBarcode = item.PalletBarcode;
                    pickOrder.Roadway = cellobj.RoutewayId.ToString();
                    pickOrder.LocationCode = cellobj.Code;
                    pickOrder.LocationDepth = cellobj.DepthIndex;
                    if (inventoryModel.AreaCode.Contains("L"))
                        pickOrder.Status = 4;
                    else
                        pickOrder.Status = 5;
                    pickOrder.Qty = 0;
                    pickOrder.MaterialId = inventoryModel.MaterialId;
                    pickOrder.MaterialCode = inventoryModel.MaterialCode;
                    pickOrder.MaterialName = inventoryModel.MaterialName;
                    pickOrder.MaterialKeyId = inventoryModel.MaterialKeyId;
                    pickOrder.BatchNo = inventoryModel.BatchNo;
                    pickOrder.SourceType = 2;
                    pickOrder.RelatedOrderDetailId = 0;
                    pickOrder.CreateDate = DateTime.Now;
                    _pickingOrderRepository.AddEntity(pickOrder);
                    PickingOrderDetail pickOrderDetail = new PickingOrderDetail();
                    pickOrderDetail.Id = YitIdHelper.NextId();
                    pickOrderDetail.OrderId = pickOrder.Id;
                    pickOrderDetail.PalletBarcode = item.PalletBarcode;
                    pickOrderDetail.MaterialBarcode = inventoryModel.MaterialCode;
                    _pickingOrderDetailRepository.AddEntity(pickOrderDetail);
                    #endregion
                    #endregion
                    //新增物料
                    if (IsAdd)
                    {
                        _inventoryRepository.DelEntity(inventoryModel);
                        if (item.Qty < 0 || item.Qty == null)
                        {
                            message = "数量有误！";
                            _unitOfWork.RollbackChanges();
                            result = false;
                        }
                        var rbobj = _receivingBillRepository.QueryEntityById(rbdobj.BillId);
                        if (rbobj == null)
                        {
                            message = "收货单有误";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbobj.Status == 2)
                        {
                            message = "收货单已完成";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbdobj.ReceivedQty + item.Qty > rbobj.TotalQty)
                        {
                            message = "已收货数量不能大于总数量！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbdobj.ReceivedQty + item.Qty == rbobj.TotalQty)
                        {
                            rbobj.Status = 2;
                            rbdobj.ReceivedQty += (decimal)item.Qty;
                            _receivingBillRepository.UpdEntity(rbobj);
                            _receivingBillDetailRepository.UpdEntity(rbdobj);
                        }
                        else
                        {
                            rbobj.Status = 1;
                            rbdobj.ReceivedQty += (decimal)item.Qty;
                            _receivingBillRepository.UpdEntity(rbobj);
                            _receivingBillDetailRepository.UpdEntity(rbdobj);
                        }
                        var mobj = mlist.FirstOrDefault(x => x.Id == (long)rbdobj.MaterialId);
                        if (mobj == null)
                        {
                            message = "物料信息有误！";
                            return false;
                        }
                        var maxqty = mobj.MaxSafetyStock;
                        var cobj = clist.FirstOrDefault(x => x.Code == m.Cell);
                        if (cobj == null)
                        {
                            message = "找不到仓位信息！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        #region 入库单
                        ReceivingOrderDetail receivingOrder = new ReceivingOrderDetail();
                        receivingOrder.OrderSn = m.BillNo;
                        //本地入库
                        receivingOrder.BillType = rbobj.BillType;
                        receivingOrder.WarehouseId = cobj.WhId;
                        receivingOrder.WarehouseCode = cobj.WhCode;
                        receivingOrder.WarehouseName = cobj.WhName;
                        receivingOrder.AreaCode = cobj.AreaCode;
                        receivingOrder.AreaName = cobj.AreaName;
                        receivingOrder.SupplierId = rbobj.SupplierId;
                        receivingOrder.SupplierName = rbobj.SupplierName;
                        receivingOrder.CustomerId = rbobj.CustomerId;
                        receivingOrder.CustomerName = rbobj.CustomerName;
                        receivingOrder.MaterialId = rbdobj.MaterialId;
                        receivingOrder.MaterialCode = rbdobj.MaterialCode;
                        receivingOrder.MaterialName = rbdobj.MaterialName;
                        receivingOrder.MaterialTypeCode = rbdobj.MaterialTypeCode;
                        receivingOrder.MaterialTypeName = rbdobj.MaterialTypeName;
                        receivingOrder.UnitId = mobj.UnitId;
                        receivingOrder.UnitName = mobj.UnitName;
                        receivingOrder.BatchNo = rbdobj.BatchNo;
                        //订单来源默认手动创建
                        receivingOrder.SourceType = 2;
                        //质检状态默认为合格
                        receivingOrder.QualityState = 1;
                        //质量状态
                        receivingOrder.Status = 3;
                        receivingOrder.ReceivedQty = item.Qty;
                        receivingOrder.PackagedQty = 0;
                        receivingOrder.PackQty = 0;
                        receivingOrder.BatchNoExplain = rbdobj.BatchNoExplain;
                        receivingOrder.OutFactoryDate = rbdobj.OutFactoryDate;
                        receivingOrder.ProduceFactory = rbdobj.ProduceFactory;
                        receivingOrder.ProductDate = rbdobj.ProductDate;
                        receivingOrder.ExpireDate = rbdobj.ExpireDate;
                        receivingOrder.Qty = item.Qty;
                        receivingOrder.PalletBarcode = item.PalletBarcode;
                        receivingOrder.ReceivingBillDetailId = rbdobj.Id;
                        receivingOrder.ReceivingBillId = rbobj.Id;
                        #region 审计字段
                        receivingOrder.CreateUserId = m.NowUserId;
                        receivingOrder.CreateUserName = m.NowUserName;
                        #endregion
                        //采购订单行项目类型
                        receivingOrder.PurOrderLineType = 0;
                        receivingOrder.StackedQty = item.Qty;
                        receivingOrder.LocationId = cobj.Id;
                        receivingOrder.LocationCode = cobj.Code;
                        receivingOrder.LocationName = cobj.Name;
                        _receivingOrderDetailRepository.AddEntity(receivingOrder);
                        if (_unitOfWork.SaveChangesEntity() == false)
                        {
                            message = "添加入库单失败!";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        #endregion
                        #region 增加库存
                        Inventory inventory = new Inventory();
                        inventory.WarehouseId = cobj.WhId;
                        inventory.WarehouseCode = cobj.WhCode;
                        inventory.WarehouseName = cobj.WhName;
                        inventory.AreaCode = cobj.AreaCode;
                        inventory.AreaName = cobj.AreaName;
                        inventory.AreaId = cobj.AreaId;
                        inventory.LocationId = cobj.Id;
                        inventory.LocationCode = cobj.Code;
                        inventory.LocationDepth = cobj.DepthIndex;
                        inventory.LocationName = cobj.Name;
                        if (inventory.AreaCode.Contains('L'))
                            inventory.Status = 4;
                        else
                            inventory.Status = 1;
                        inventory.PalletBarcode = item.PalletBarcode;
                        inventory.ParentPalletBarcode = item.PalletBarcode;
                        inventory.RelatedOrderDetailId = receivingOrder.Id;
                        inventory.BillType = (int)receivingOrder.BillType.GetValueOrDefault();
                        inventory.IsLock = false;
                        inventory.MaterialId = receivingOrder.MaterialId;
                        inventory.MaterialCode = receivingOrder.MaterialCode;
                        inventory.MaterialName = receivingOrder.MaterialName;
                        inventory.CustomerId = receivingOrder.CustomerId;
                        inventory.InStockDate = DateTime.Now;
                        inventory.CustomerName = receivingOrder.CustomerName;
                        inventory.SupplierId = receivingOrder.SupplierId;
                        inventory.SupplierName = receivingOrder.SupplierName;
                        inventory.HasSkuDetail = true;
                        inventory.PutawayQty = receivingOrder.Qty;
                        inventory.UnitId = receivingOrder.UnitId;
                        inventory.UnitName = receivingOrder.UnitName;
                        inventory.MaterialKeyId = receivingOrder.MaterialKeyId;
                        inventory.BatchNo = receivingOrder.BatchNo;
                        inventory.ExpireDate = receivingOrder.ExpireDate;
                        inventory.ProductDate = receivingOrder.ProductDate;
                        inventory.MaterialTypeCode = receivingOrder.MaterialTypeCode;
                        inventory.MaterialTypeName = receivingOrder.MaterialTypeName;
                        inventory.PickedQty = 0;
                        inventory.ErplocationCode = cobj.Erpcode;
                        inventory.RoutewayId = cobj.RoutewayId;
                        inventory.StackingStorageId = 0;
                        inventory.LocationHeightType = cobj.HeightType;
                        inventory.LogicalPartCode = receivingOrder.LogicalPartCode;//按单据来
                        inventory.LocationColumnNo = cobj.ColumnNo;
                        inventory.LocationLayerNo = cobj.LayerNo;
                        inventory.LocationDistanceValue = Convert.ToInt32(cobj.IsMaxDepth);
                        inventory.LocationLineNo = cobj.LineNo;
                        inventory.AvailableQty = receivingOrder.ReceivedQty;
                        inventory.AllocateQty = 0;
                        inventory.CreateUserId = m.NowUserId;
                        inventory.CreateUserName = m.NowUserName;
                        _inventoryRepository.AddEntity(inventory);
                        if (!_unitOfWork.SaveChangesEntity())
                        {
                            message = "保存库存失败！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        //库存明细保存
                        InventoryDetail inventoryDetail = new InventoryDetail()
                        {
                            Id = YitIdHelper.NextId(),
                            InventoryId = inventory.Id,
                            PalletBarcode = item.PalletBarcode,
                            SkuNum = receivingOrder.Qty,
                            IsSku = false,
                        };
                        _inventoryDetailRepository.AddEntity(inventoryDetail);
                        #endregion
                        if (inventory.AvailableQty > maxqty)
                        {
                            message = "调增后的库存大于该物料最大库存预警！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        startqty = inventory.AvailableQty;
                        //添加指令
                        Instruct instruct = new Instruct
                        {
                            Status = 4,
                            WarehouseCode = inventory.WarehouseCode,
                            ToLocation = inventory.LocationCode,
                            WorkDeviceType = 1,
                            InstructType = 6,
                            Action = 0,
                            RelatedOrderId = inventory.RelatedOrderDetailId,
                            DeviceCode = "",
                            ExpectedToLocation = inventory.LocationCode,
                            InstructIndex = 1,
                            PalletBarcode = inventory.PalletBarcode,
                            Priority = 9999,
                            Qty = (decimal)inventory.AvailableQty,
                            BusinessType = (int)EmBusinessType.In,
                            EndTime = DateTime.Now,
                            ScanedBarcode = inventory.PalletBarcode
                        };
                        _instructRepository.AddEntity(instruct);
                        #region 保存上架单主表
                        string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        string putawayCode = "RRT" + str;
                        PutawayOrder putawayOrder = new PutawayOrder();
                        putawayOrder.Id = YitIdHelper.NextId();
                        putawayOrder.Code = putawayCode;
                        putawayOrder.BillType = 1;
                        putawayOrder.RelatedOrderDetailId = inventory.Id;
                        putawayOrder.PalletBarcode = inventory.PalletBarcode;
                        putawayOrder.LocationCode = inventory.LocationCode;
                        putawayOrder.LocationDepth = inventory.LocationDepth == 0 ? null : inventory.LocationDepth;
                        putawayOrder.Status = 5;
                        putawayOrder.Qty = inventory.AvailableQty;
                        putawayOrder.MaterialId = inventory.MaterialId;
                        putawayOrder.MaterialCode = inventory.MaterialCode;
                        putawayOrder.MaterialName = inventory.MaterialName;
                        putawayOrder.MaterialKeyId = inventory.MaterialKeyId;
                        putawayOrder.SourceType = 1;
                        putawayOrder.Roadway = inventory.RoutewayId.ToString();
                        _putawayOrderRepository.AddEntity(putawayOrder);
                        if (!_unitOfWork.SaveChangesEntity())
                        {
                            message = "保存上架单！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        #endregion
                        //库存流水
                        InventoryLog inventoryLog = new InventoryLog()
                        {
                            Id = YitIdHelper.NextId(),
                            SourceType = 0,
                            SourceSn = receivingOrder.OrderSn,
                            WarehouseId = receivingOrder.WarehouseId,
                            WarehouseName = receivingOrder.WarehouseName,
                            AreaName = inventory.AreaName,
                            AreaId = inventory.AreaId,
                            LocationCode = inventory.LocationCode,
                            PalletBarcode = inventory.PalletBarcode,
                            MaterialId = receivingOrder.MaterialId,
                            MaterialCode = receivingOrder.MaterialCode,
                            MaterialName = receivingOrder.MaterialName,
                            BatchNo = receivingOrder.BatchNo,
                            StartQty = 0,
                            ChangeQty = item.Qty,
                            EndQty = inventory.AvailableQty,
                            BaseUnitId = receivingOrder.UnitId,
                            BaseUnitName = receivingOrder.UnitName,
                            CreateDate = DateTime.Now,
                            Remark = "拣选入库加新物料"
                        };
                        _inventoryLogRepository.AddEntity(inventoryLog);
                    }
                    else
                    {
                        //库存中已有物料增加数量
                        if (item.Qty < 0 || item.Qty == null)
                        {
                            message = "数量有误！";
                            result = true;
                        }
                        var rbobj = _receivingBillRepository.QueryEntityById(rbdobj.BillId);
                        if (rbobj == null)
                        {
                            message = "收货单有误";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbobj.Status == 2)
                        {
                            message = "收货单已完成";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbdobj.ReceivedQty + item.Qty > rbobj.TotalQty)
                        {
                            message = "已收货数量不能大于总数量！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (rbdobj.ReceivedQty + item.Qty == rbobj.TotalQty)
                        {
                            rbobj.Status = 2;
                            rbdobj.ReceivedQty += (decimal)item.Qty;
                            _receivingBillRepository.UpdEntity(rbobj);
                            _receivingBillDetailRepository.UpdEntity(rbdobj);
                        }
                        else
                        {
                            rbobj.Status = 1;
                            rbdobj.ReceivedQty += (decimal)item.Qty;
                            _receivingBillRepository.UpdEntity(rbobj);
                            _receivingBillDetailRepository.UpdEntity(rbdobj);
                        }
                        var mobj = mlist.FirstOrDefault(x => x.Id == (long)rbdobj.MaterialId);
                        if (mobj == null)
                        {
                            message = "物料信息有误！";
                            return false;
                        }
                        var maxqty = mobj.MaxSafetyStock;
                        var cobj = clist.FirstOrDefault(x => x.Code == m.Cell);
                        if (cobj == null)
                        {
                            message = "找不到仓位信息！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        #region 入库单
                        ReceivingOrderDetail receivingOrder = new ReceivingOrderDetail();
                        receivingOrder.OrderSn = m.BillNo;
                        //本地入库
                        receivingOrder.BillType = rbobj.BillType;
                        receivingOrder.WarehouseId = cobj.WhId;
                        receivingOrder.WarehouseCode = cobj.WhCode;
                        receivingOrder.WarehouseName = cobj.WhName;
                        receivingOrder.AreaCode = cobj.AreaCode;
                        receivingOrder.AreaName = cobj.AreaName;
                        receivingOrder.SupplierId = rbobj.SupplierId;
                        receivingOrder.SupplierName = rbobj.SupplierName;
                        receivingOrder.CustomerId = rbobj.CustomerId;
                        receivingOrder.CustomerName = rbobj.CustomerName;
                        receivingOrder.MaterialId = rbdobj.MaterialId;
                        receivingOrder.MaterialCode = rbdobj.MaterialCode;
                        receivingOrder.MaterialName = rbdobj.MaterialName;
                        receivingOrder.MaterialTypeCode = rbdobj.MaterialTypeCode;
                        receivingOrder.MaterialTypeName = rbdobj.MaterialTypeName;
                        receivingOrder.UnitId = mobj.UnitId;
                        receivingOrder.UnitName = mobj.UnitName;
                        receivingOrder.BatchNo = rbdobj.BatchNo;
                        //订单来源默认手动创建
                        receivingOrder.SourceType = 2;
                        //质检状态默认为合格
                        receivingOrder.QualityState = 1;
                        //质量状态
                        receivingOrder.Status = 3;
                        receivingOrder.ReceivedQty = item.Qty;
                        receivingOrder.PackagedQty = 0;
                        receivingOrder.PackQty = 0;
                        receivingOrder.BatchNoExplain = rbdobj.BatchNoExplain;
                        receivingOrder.OutFactoryDate = rbdobj.OutFactoryDate;
                        receivingOrder.ProduceFactory = rbdobj.ProduceFactory;
                        receivingOrder.ProductDate = rbdobj.ProductDate;
                        receivingOrder.ExpireDate = rbdobj.ExpireDate;
                        receivingOrder.Qty = item.Qty;
                        receivingOrder.PalletBarcode = item.PalletBarcode;
                        receivingOrder.ReceivingBillDetailId = rbdobj.Id;
                        receivingOrder.ReceivingBillId = rbobj.Id;
                        #region 审计字段
                        receivingOrder.CreateUserId = m.NowUserId;
                        receivingOrder.CreateUserName = m.NowUserName;
                        #endregion
                        //采购订单行项目类型
                        receivingOrder.PurOrderLineType = 0;
                        receivingOrder.StackedQty = item.Qty;
                        receivingOrder.LocationId = cobj.Id;
                        receivingOrder.LocationCode = cobj.Code;
                        receivingOrder.LocationName = cobj.Name;
                        _receivingOrderDetailRepository.AddEntity(receivingOrder);
                        if (_unitOfWork.SaveChangesEntity() == false)
                        {
                            message = "添加入库单失败!";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        #endregion
                        if (inventoryModel.AreaCode.Contains('L'))
                            inventoryModel.IsLock = true;
                        else
                            inventoryModel.IsLock = false;
                        inventoryModel.Status = 4;
                        if (inventoryModel.AvailableQty + item.Qty > maxqty)
                        {
                            message = "调增后的库存大于该物料最大库存预警！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        startqty = inventoryModel.AvailableQty;
                        inventoryModel.AvailableQty += item.Qty;
                        _inventoryRepository.UpdEntity(inventoryModel);
                        //出库单单子明细
                        var sllist = _shippingLockCellRepository.GetEntityWhereAll(x => x.InventoryId == inventoryModel.Id && x.Status != 4);
                        foreach (var item2 in sllist)
                        {
                            item2.InventoryQty = inventoryModel.AvailableQty;
                        }
                        //添加指令
                        Instruct instruct = new Instruct
                        {
                            Status = 4,
                            WarehouseCode = inventoryModel.WarehouseCode,
                            ToLocation = inventoryModel.LocationCode,
                            WorkDeviceType = 1,
                            InstructType = 6,
                            Action = 0,
                            RelatedOrderId = inventoryModel.RelatedOrderDetailId,
                            DeviceCode = "",
                            ExpectedToLocation = inventoryModel.LocationCode,
                            InstructIndex = 1,
                            PalletBarcode = inventoryModel.PalletBarcode,
                            Priority = 9999,
                            Qty = (decimal)inventoryModel.AvailableQty,
                            BusinessType = (int)EmBusinessType.In,
                            EndTime = DateTime.Now,
                            ScanedBarcode = inventoryModel.PalletBarcode
                        };
                        _instructRepository.AddEntity(instruct);
                        #region 保存上架单主表
                        string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        string putawayCode = "RRT" + str;
                        PutawayOrder putawayOrder = new PutawayOrder();
                        putawayOrder.Id = YitIdHelper.NextId();
                        putawayOrder.Code = putawayCode;
                        putawayOrder.BillType = 1;
                        putawayOrder.RelatedOrderDetailId = inventoryModel.Id;
                        putawayOrder.PalletBarcode = inventoryModel.PalletBarcode;
                        putawayOrder.LocationCode = inventoryModel.LocationCode;
                        putawayOrder.LocationDepth = inventoryModel.LocationDepth == 0 ? null : inventoryModel.LocationDepth;
                        putawayOrder.Status = 5;
                        putawayOrder.Qty = inventoryModel.AvailableQty;
                        putawayOrder.MaterialId = inventoryModel.MaterialId;
                        putawayOrder.MaterialCode = inventoryModel.MaterialCode;
                        putawayOrder.MaterialName = inventoryModel.MaterialName;
                        putawayOrder.MaterialKeyId = inventoryModel.MaterialKeyId;
                        putawayOrder.SourceType = 1;
                        putawayOrder.Roadway = inventoryModel.RoutewayId.ToString();
                        _putawayOrderRepository.AddEntity(putawayOrder);
                        if (!_unitOfWork.SaveChangesEntity())
                        {
                            message = "保存上架单失败！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        #endregion
                        //库存流水
                        InventoryLog inventoryLog = new InventoryLog()
                        {
                            Id = YitIdHelper.NextId(),
                            SourceType = 0,
                            SourceSn = receivingOrder.OrderSn,
                            WarehouseId = receivingOrder.WarehouseId,
                            WarehouseName = receivingOrder.WarehouseName,
                            AreaName = inventoryModel.AreaName,
                            AreaId = inventoryModel.AreaId,
                            LocationCode = inventoryModel.LocationCode,
                            PalletBarcode = inventoryModel.PalletBarcode,
                            MaterialId = receivingOrder.MaterialId,
                            MaterialCode = receivingOrder.MaterialCode,
                            MaterialName = receivingOrder.MaterialName,
                            BatchNo = receivingOrder.BatchNo,
                            StartQty = startqty,
                            ChangeQty = item.Qty,
                            EndQty = inventoryModel.AvailableQty,
                            BaseUnitId = receivingOrder.UnitId,
                            BaseUnitName = receivingOrder.UnitName,
                            CreateDate = DateTime.Now,
                            Remark = "拣选入库加数量"
                        };
                        _inventoryLogRepository.AddEntity(inventoryLog);
                    }
                    result = _unitOfWork.SaveChangesEntity();
                    if (!result)
                    {
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    else
                    {
                        if (Config.IsDev == false)
                        {
                            //出库
                            WcsTaskDto wcsTaskDto2 = new WcsTaskDto
                            {
                                TaskCode = pickOrder.Code,
                                Tunnel = Convert.ToInt32(pickOrder.LocationCode.Substring(5, 1)),
                                Row = Convert.ToInt32(pickOrder.LocationCode.Substring(7, 1)),
                                Bay = Convert.ToInt32(pickOrder.LocationCode.Substring(9, 1)),
                                Level = Convert.ToInt32(pickOrder.LocationCode.Substring(11, 1)),
                                PalletCode = pickOrder.PalletBarcode,
                                Qty = pickOrder.Qty
                            };
                            wcsTaskDto2.Station = wcsTaskDto2.Tunnel == 3 ? EmStation.S107 : EmStation.S106;
                            var wcsresult2 = _wcsHttpClient.OutTaskApi(wcsTaskDto2);
                            if (wcsresult2.Code != EmApiResCode.Success)
                            {
                                message = wcsresult2.Msg;
                                result = false;
                                _unitOfWork.RollbackChanges();
                                return false;
                            }
                            else
                            {
                                InterfaceLog interfaceLog = new InterfaceLog();
                                interfaceLog.Name = "LpStationStatus";
                                interfaceLog.Url = "wcs/ExternalApi/LpStationStatus";
                                interfaceLog.CallWay = 2;
                                interfaceLog.CallWayStr = "POST";
                                interfaceLog.InParam = JsonConvert.SerializeObject(m);
                                interfaceLog.OutParam = wcsresult2.Msg + $"(出库)托盘{inventoryModel.PalletBarcode} 仓位{inventoryModel.LocationCode}";
                                interfaceLog.ExecDate = DateTime.Now;
                                interfaceLog.FinishedDate = DateTime.Now;
                                interfaceLog.Status = 1;
                                _interfaceLogRepository.AddEntity(interfaceLog);
                                _unitOfWork.SaveChangesEntity();
                            }
                        }
                        _unitOfWork.CommitChanges();
                    }
                }
                return true;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }

        }

        #region 出库产生移库逻辑处理
        private bool ShippingTransferBinInventory(string fromcellcode, string trancellcode, string acode, string pacode, out string message)
        {
            message = string.Empty;
            #region 修改库存状态
            var toCell = GetTranCellCode(acode, out message);
            if (toCell == null)
            {
                message = "目标仓位不存在或者已被占用";
                return false;
            }
            else
            {
                toCell.FullStatus = 1;
                toCell.IsLock = true;
                toCell.BusinessType = 1;
                toCell.ModifyDate = DateTime.Now;
                _cellRepository.UpdEntity(toCell);
            }
            bool isshipplost = false;
            var slocklist = _shippingLockCellRepository.GetEntityWhereAll(x => x.CellCode == trancellcode && x.Status == 0).ToList();
            foreach (var item2 in slocklist)
            {
                //标记状态列
                item2.CellId = toCell.Id;
                item2.CellCode = toCell.Code;
                item2.CellName = toCell.Name;
                item2.Status = 3;
                isshipplost = true;
                _shippingLockCellRepository.UpdEntity(item2);
            }
            var tinventorylist = _inventoryRepository.GetEntityWhereAll(it => it.LocationCode == trancellcode).ToList();
            foreach (var inventory in tinventorylist)
            {
                inventory.LocationId = toCell.Id;
                inventory.LocationName = toCell.Name;
                inventory.LocationCode = toCell.Code;
                inventory.LocationDepth = toCell.DepthIndex;
                inventory.LocationLineNo = toCell.LineNo;
                inventory.LocationLayerNo = toCell.LayerNo;
                inventory.LocationColumnNo = toCell.ColumnNo;
                inventory.Status = 2;
                inventory.LocationHeightType = toCell.HeightType;
                inventory.IsLock = true;
                inventory.RoutewayId = toCell.RoutewayId;
                inventory.ErplocationCode = toCell.Erpcode;
                if (isshipplost)
                    inventory.Remark = "系统移库";
                _inventoryRepository.UpdEntity(inventory);
                #region 关联的入库单做处理
                if (inventory.RelatedOrderDetailId == null)
                {
                    message = "关联的入库单id有误！";
                    return false;
                }
                var revingobj = _receivingOrderDetailRepository.QueryEntityById((long)inventory.RelatedOrderDetailId);
                if (revingobj == null)
                {
                    message = "入库单明细不存在或已被删除";
                    return false;
                }
                #region 指令管理
                Instruct instruct = null;
                instruct = new Instruct
                {
                    WarehouseCode = toCell.WhCode,
                    Status = 2,
                    FromLocation = trancellcode,
                    ToLocation = toCell.Code,
                    StackingStorageId = 0,
                    WorkDeviceType = 1,
                    InstructType = 3,
                    Action = 0,
                    RelatedOrderId = revingobj.Id,
                    RelatedOrderDetailId = 0,
                    DeviceCode = "",
                    ExpectedToLocation = toCell.Code,
                    InstructIndex = 1,
                    PalletBarcode = pacode,
                    ScanedBarcode = pacode,
                    Priority = 9999,
                    Qty = inventory.AvailableQty == null ? 0 : (decimal)inventory.AvailableQty,
                    FinishedQty = 0,
                    CreateDate = DateTime.Now,
                    BusinessType = (int)EmBusinessType.Move,
                    BillType = (int)revingobj.BillType.GetValueOrDefault(),
                };
                _instructRepository.AddEntity(instruct);
                #endregion
                #endregion


                #endregion
                #region 上架单
                string tstr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string traawayCode = "TRA" + tstr;
                PutawayOrder putawayOrder = new PutawayOrder();
                putawayOrder.Id = YitIdHelper.NextId();
                putawayOrder.Code = traawayCode;
                putawayOrder.RelatedOrderDetailId = tinventorylist.First().RelatedOrderDetailId;
                putawayOrder.StackingStorageId = 0;
                putawayOrder.PalletBarcode = tinventorylist.First().PalletBarcode;
                putawayOrder.LocationCode = toCell.Code;
                putawayOrder.LocationDepth = toCell.DepthIndex == 0 ? null : toCell.DepthIndex;
                putawayOrder.Status = 4;
                putawayOrder.Qty = tinventorylist.First().AvailableQty;
                putawayOrder.CreateDate = DateTime.Now;
                putawayOrder.MaterialId = tinventorylist.First().MaterialId;
                putawayOrder.MaterialCode = tinventorylist.First().MaterialCode;
                putawayOrder.MaterialName = tinventorylist.First().MaterialName;
                putawayOrder.MaterialKeyId = tinventorylist.First().MaterialKeyId;
                putawayOrder.BatchNo = tinventorylist.First().BatchNo;
                putawayOrder.CreateUserId = 0;
                putawayOrder.CreateUserName = "系统";
                putawayOrder.SourceType = 3;
                putawayOrder.SiteCode = "";
                _putawayOrderRepository.AddEntity(putawayOrder);
            }
            var pallobj = _palletRepository.QueryEntityWhere(x => x.LocationCode == trancellcode);
            if (pallobj != null)
            {
                pallobj.LocationName = toCell.Name;
                pallobj.LocationCode = toCell.Code;
            }

            #endregion
            return _unitOfWork.SaveChangesEntity();
        }

        private DFGK_WMS.Model.Models.Cell? GetTranCellCode(string acode, out string message)
        {
            message = string.Empty;
            if (string.IsNullOrEmpty(acode))
            {
                message = "库区编码有误！";
                return null;
            }
            DFGK_WMS.Model.Models.Cell? cellobj = new DFGK_WMS.Model.Models.Cell();
            //获取所有库区
            var areaobj = _areaRepository.QueryIsEntityWhere(x => x.Code == acode && x.Status == 1);
            if (areaobj == null || areaobj.WhId == null)
            {
                message = "库区不存在或已被禁用!";
                return null;
            }
            long? wid = areaobj.WhId;
            //获取所有库房
            var warehouseobj = _warehouseRepository.QueryIsEntityWhere(x => x.Id == wid && x.Status == 1);
            if (warehouseobj == null)
            {
                message = "库房不存在或已被禁用!";
                return null;
            }

            //获取所有巷道
            var routewayQuery = _routewayRepository.GetEntityWhereAll(x => x.WhId == wid && x.Status == 1);
            if (routewayQuery == null)
            {
                message = "无可用巷道!";
                return null;
            }
            List<long> enabledRoutewayIds = routewayQuery.Select(t => t.Id).ToList();//只取巷道id
                                                                                     // 获取所有货架
            var shelves = _shelfRepository.GetEntityWhereAll(x => x.WhId == wid && x.AreaId == areaobj.Id && x.Status == 1 && enabledRoutewayIds.Contains((long)x.RoutewayId));
            if (shelves == null)
            {
                message = "无可用货架!";
                return null;
            }
            List<long> enabledShelves = shelves.Select(t => t.Id).ToList();//只取货架id
                                                                           //获取所有可用仓位
            var cellQuery = _cellRepository
                .GetEntityWhereAll(x => x.AreaCode == acode
                                        && x.Status == 1
                                        && x.FullStatus == 0
                                        && x.IsLock == false
                                        && enabledRoutewayIds.Contains((long)x.RoutewayId)
                                        && enabledShelves.Contains((long)x.ShelfId)).ToList();
            if (cellQuery == null)
            {
                message = "无可用仓位!";
                return null;
            }
            cellobj = cellQuery.Where(x => x.IsMaxDepth == true).OrderByDescending(c => c.DepthIndex)
                                .ThenBy(c => c.LayerNo)
                                .ThenBy(c => c.ColumnNo)
                                .ThenBy(c => c.LineNo)
                                .FirstOrDefault();
            if (cellobj != null)
            {
                return cellobj;
            }
            else
            {
                cellobj = cellQuery.Where(x => x.IsMaxDepth == false).OrderByDescending(c => c.DepthIndex)
                              .ThenBy(c => c.LayerNo)
                              .ThenBy(c => c.ColumnNo)
                              .ThenBy(c => c.LineNo)
                              .FirstOrDefault();
                if (cellobj != null)
                {
                    return cellobj;
                }
            }
            if (cellobj == null)
                message = "无可用仓位!";
            return null;
        }
        #endregion

        #region 组垛私有方法
        /// <summary>
        /// 添加入库单
        /// </summary>
        /// <param name="m"></param>
        /// <param name="palletBarcode"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool AddReceivingOrderDetail(ReceivingBillDetail m, decimal receivedQty, long nowuserid, string nowusername, string palletBarcode, out string message)
        {
            message = string.Empty;
            if (m.ReceivedQty <= 0)
            {
                message = "收货数量";
                _unitOfWork.RollbackChanges();
                return false;
            }

            var area = _areaRepository.QueryEntityWhere(d => d.Id == m.AreaId);
            //通过Aid 判断平库 立库
            if (area == null)
            {
                if (string.IsNullOrEmpty(palletBarcode))
                {
                    message = "托盘有误";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
            }
          
            var reobj = _receivingBillRepository.QueryEntityById(m.BillId);
            if (reobj == null)
            {
                message = "收货单有误";
                _unitOfWork.RollbackChanges();
                return false;
            }
            var mobj = _materialRepository.QueryEntityById(m.MaterialId);
            if (mobj == null)
            {
                message = "物料信息有误！";
                _unitOfWork.RollbackChanges();
                return false;
            }
            var aobj = _areaRepository.QueryEntityById(m.AreaId);
            if (aobj == null)
            {
                message = "库区信息有误！";
                _unitOfWork.RollbackChanges();
                return false;
            }
            ReceivingOrderDetail receivingOrder = new ReceivingOrderDetail();
            receivingOrder.OrderSn = m.BillNo;
            //本地入库
            receivingOrder.BillType = reobj.BillType;
            receivingOrder.WarehouseId = reobj.WarehouseId;
            receivingOrder.WarehouseCode = reobj.WarehouseCode;
            receivingOrder.WarehouseName = reobj.WarehouseName;
            receivingOrder.AreaCode = aobj.Code;
            receivingOrder.AreaName = aobj.Name;
            receivingOrder.SupplierId = reobj.SupplierId;
            receivingOrder.SupplierName = reobj.SupplierName;
            receivingOrder.CustomerId = reobj.CustomerId;
            receivingOrder.CustomerName = reobj.CustomerName;
            receivingOrder.MaterialId = m.MaterialId;
            receivingOrder.MaterialCode = m.MaterialCode;
            receivingOrder.MaterialName = m.MaterialName;
            receivingOrder.MaterialTypeCode = m.MaterialTypeCode;
            receivingOrder.MaterialTypeName = m.MaterialTypeName;
            receivingOrder.UnitId = mobj.UnitId;
            receivingOrder.UnitName = mobj.UnitName;
            receivingOrder.BatchNo = m.BatchNo;
            //订单来源默认手动创建
            receivingOrder.SourceType = 2;
            //质检状态默认为合格
            receivingOrder.QualityState = 1;
            //质量状态
            receivingOrder.Status = 0;
            receivingOrder.ReceivedQty = receivedQty;
            receivingOrder.PackagedQty = 0;
            receivingOrder.PackQty = 0;
            receivingOrder.BatchNoExplain = m.BatchNoExplain;
            receivingOrder.OutFactoryDate = m.OutFactoryDate;
            receivingOrder.ProduceFactory = m.ProduceFactory;
            receivingOrder.ProductDate = m.ProductDate;
            receivingOrder.ExpireDate = m.ExpireDate;
            receivingOrder.Qty = receivedQty;
            receivingOrder.PalletBarcode = palletBarcode;
            receivingOrder.ReceivingBillDetailId = m.Id;
            receivingOrder.ReceivingBillId = reobj.Id;
            //这个指端指的stockcode
            receivingOrder.Erpcode = reobj.StockCode;
            #region 审计字段
            receivingOrder.CreateUserId = nowuserid;
            receivingOrder.CreateUserName = nowusername;
            //receivingOrder.AuditUserId = m.NowUserId;
            //receivingOrder.AuditUserName = m.NowUserRealName;
            //receivingOrder.AuditDate = DateTime.Now;
            //receivingOrder.SubmitUserId = m.NowUserId;
            //receivingOrder.SubmitUserName = m.NowUserRealName;
            //receivingOrder.SubmitDate = DateTime.Now;
            //receivingOrder.ReceivingBillId = m.Id;
            #endregion
            //采购订单行项目类型
            receivingOrder.PurOrderLineType = 0;
            receivingOrder.StackedQty = receivedQty;
            if (!string.IsNullOrEmpty(m.StoLocation))
                receivingOrder.LocationCode = m.StoLocation;
            _receivingOrderDetailRepository.AddEntity(receivingOrder);
            if (_unitOfWork.SaveChangesEntity() == false)
            {
                message = "添加入库单失败!";
                _unitOfWork.RollbackChanges();
                return false;
            }
            return AddReceivingOrderDetailStackingStorage(receivingOrder,  out message);
        }

        /// <summary>
        /// 添加组垛
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool AddReceivingOrderDetailStackingStorage(ReceivingOrderDetail m, out string message)
        {
            message = string.Empty;
            var stationobj = _stationRepository.GetEntityWhereAll(x => x.FunctionType == 1);
            //if (!stationobj.Any())
            //{
            //    message = "请配置站台!";
            //    return false;
            //}
            if (m.PalletBarcode!=null)
            {
             var haveInventory= _inventoryRepository.QueryEntityWhere(d => d.PalletBarcode == m.PalletBarcode);
                if (haveInventory != null && haveInventory.AreaCode.Contains("P"))
                {
                    message = "库存存在,不同规格进行存储";
                    m.LocationCode = haveInventory.LocationCode;
                }
            }
            //是否有手动填写仓位
            if (!string.IsNullOrEmpty(m.LocationCode))
            {
                //锁仓位
                var cells = _cellRepository.QueryEntityWhere(x => x.Code == m.LocationCode);
                if (cells == null)
                { 
                }
                //if (cells.FullStatus == 1 || cells.Status != 1 || cells.BusinessType != 0 || cells.IsLock == true)
                //{
                //    message = "已选择的仓位状态已被占用或异常!";
                //    return false;
                //}
                cells.BusinessType = 1;
                cells.IsLock = true;
                cells.FullStatus = 1;
                _cellRepository.UpdEntity(cells);
                StackingStorage stackingStorages = new StackingStorage();
                stackingStorages.WarehouseName = m.WarehouseName;
                stackingStorages.WarehouseCode = m.WarehouseCode;
                stackingStorages.BillType = 1;
                stackingStorages.RelatedOrderDetailId = m.Id;
                stackingStorages.Status = 1;
                stackingStorages.PalletBarcode = m.PalletBarcode;
                stackingStorages.Qty = m.Qty;
                stackingStorages.PackQty = 1;
                stackingStorages.MaterialId = m.MaterialId;
                stackingStorages.MaterialCode = m.MaterialCode;
                stackingStorages.MaterialName = m.MaterialName;
                stackingStorages.MaterialKeyId = m.MaterialKeyId;
                stackingStorages.BatchNo = m.BatchNo;
                stackingStorages.Fifodate = DateTime.Now;
                stackingStorages.ExpectedLocation = m.LocationCode;
                _stackingStorageRepository.AddEntity(stackingStorages);
                //更新入库单状态
                m.WarehouseId = cells.WhId;
                m.WarehouseCode = cells.WhCode;
                m.WarehouseName = cells.WhName;
                m.AreaCode = cells.AreaCode;
                m.AreaName = cells.AreaName;
                m.LocationId = cells.Id;
                m.LocationName = cells.Name;
                m.LocationCode = cells.Code;
                _receivingOrderDetailRepository.UpdEntity(m);
                message = m.LocationCode;
                return _unitOfWork.SaveChangesEntity();
            }
            string cellcode = "";
            var stackobj = _stackingStorageRepository.QueryIsEntityWhere(x => x.PalletBarcode == m.PalletBarcode);
            if (stackobj != null)
                cellcode = stackobj.ExpectedLocation;

            StackingStorage stackingStorage = new StackingStorage();
            stackingStorage.WarehouseName = m.WarehouseName;
            stackingStorage.WarehouseCode = m.WarehouseCode;
            stackingStorage.BillType = 1;
            stackingStorage.RelatedOrderDetailId = m.Id;
            stackingStorage.Status = 1;
            stackingStorage.PalletBarcode = m.PalletBarcode;
            stackingStorage.Qty = m.Qty;
            stackingStorage.PackQty = 1;
            stackingStorage.MaterialId = m.MaterialId;
            stackingStorage.MaterialCode = m.MaterialCode;
            stackingStorage.MaterialName = m.MaterialName;
            stackingStorage.MaterialKeyId = m.MaterialKeyId;
            stackingStorage.BatchNo = m.BatchNo;
            stackingStorage.Fifodate = DateTime.Now;
            stackingStorage.AreaCode = m.AreaCode;
            if (!string.IsNullOrEmpty(cellcode))
            {
                stackingStorage.ExpectedLocation = cellcode;
                message = cellcode;
            }
            else
            {
                if (m.MaterialName == "空托盘")
                {
                    if (!KongGetCellCode(m.AreaCode, out message))
                    {
                        if (!GetCellCode(stackingStorage, m.Erpcode, out message))
                        {
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                    }
                    cellcode = message;
                    stackingStorage.ExpectedLocation = cellcode;
                }
                else
                {
                    if (!GetCellCode(stackingStorage,m.Erpcode,  out message))
                    {
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    cellcode = message;
                    stackingStorage.ExpectedLocation = cellcode;
                }
            }

            _stackingStorageRepository.AddEntity(stackingStorage);

            //锁仓位
            var cell = _cellRepository.QueryEntityWhere(x => x.Code == cellcode && x.AreaCode==m.AreaCode);
            if (cell == null)
            {
                message = "找不到匹配仓位!";
                return false;
            }
            cell.BusinessType = 1;
            cell.IsLock = true;
            cell.FullStatus = 1;
            _cellRepository.UpdEntity(cell);

            //更新入库单状态
            m.WarehouseId = cell.WhId;
            m.WarehouseCode = cell.WhCode;
            m.WarehouseName = cell.WhName;
            m.AreaCode = cell.AreaCode;
            m.AreaName = cell.AreaName;
            m.LocationId = cell.Id;
            m.LocationName = cell.Name;
            m.LocationCode = cell.Code;
            _receivingOrderDetailRepository.UpdEntity(m);
            return _unitOfWork.SaveChangesEntity();
        }
        /// <summary>
        /// 获取一个仓位
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool GetCellCode(string acode, out string message)
        {
            message = string.Empty;
            if (string.IsNullOrEmpty(acode))
            {
                message = "库区编码有误！";
                return false;
            }
            Cell? cellobj = new Cell();
            //获取所有库区
            var areaobj = _areaRepository.QueryIsEntityWhere(x => x.Code == acode && x.Status == 1);
            if (areaobj == null || areaobj.WhId == null)
            {
                message = "库区不存在或已被禁用!";
                return false;
            }
            long? wid = areaobj.WhId;
            //获取所有库房
            var warehouseobj = _warehouseRepository.QueryIsEntityWhere(x => x.Id == wid && x.Status == 1);
            if (warehouseobj == null)
            {
                message = "库房不存在或已被禁用!";
                return false;
            }

            //获取所有巷道
            var routewayQuery = _routewayRepository.GetEntityWhereAll(x => x.WhId == wid && x.Status == 1);
            if (!routewayQuery.Any())
            {
                message = "无可用巷道!";
                return false;
            }
            List<long> enabledRoutewayIds = routewayQuery.Select(t => t.Id).ToList();//只取巷道id

            var shelves = _shelfRepository.GetEntityWhereAll(x => x.WhId == wid && x.AreaId == areaobj.Id && x.Status == 1 && enabledRoutewayIds.Contains(x.RoutewayId ?? 0));
            if (!shelves.Any())
            {
                message = "无可用货架!";
                return false;
            }
            List<long> enabledShelves = shelves.Select(t => t.Id).ToList();//只取货架id
             //获取所有仓位
            var cellQuery = _cellRepository.GetEntityWhereAll(x => x.AreaCode == acode && x.Status == 1 && x.FullStatus == 0 && x.IsLock == false && x.BusinessType == 0 && enabledRoutewayIds.Contains(x.RoutewayId ?? 0) && enabledShelves.Contains(x.ShelfId ?? 0));
            if (!cellQuery.Any())
            {
                message = "无可用仓位!";
                return false;
            }
            cellobj = cellQuery.Where(x => x.IsMaxDepth == true).OrderByDescending(c => c.DepthIndex)
                                .ThenBy(c => c.LayerNo)
                                .ThenBy(c => c.ColumnNo)
                                .ThenBy(c => c.LineNo)
                                .FirstOrDefault();
            if (cellobj != null)
            {
                message = cellobj.Code;
                return true;
            }
            else
            {
                cellobj = cellQuery.Where(x => x.IsMaxDepth == false).OrderByDescending(c => c.DepthIndex)
                              .ThenBy(c => c.LayerNo)
                              .ThenBy(c => c.ColumnNo)
                              .ThenBy(c => c.LineNo)
                              .FirstOrDefault();
                if (cellobj != null)
                {
                    message = cellobj.Code;
                    return true;
                }
            }
            if (cellobj == null)
                message = "无可用仓位!";
            return false;
        }

        private bool KongGetCellCode(string acode, out string message)
        {
            message = string.Empty;
            if (string.IsNullOrEmpty(acode))
            {
                message = "库区编码有误！";
                return false;
            }
            Cell? cellobj = new Cell();
            //获取所有库区
            var areaobj = _areaRepository.QueryIsEntityWhere(x => x.Code == acode && x.Status == 1);
            if (areaobj == null || areaobj.WhId == null)
            {
                message = "库区不存在或已被禁用!";
                return false;
            }
            long? wid = areaobj.WhId;
            //获取所有库房
            var warehouseobj = _warehouseRepository.QueryIsEntityWhere(x => x.Id == wid && x.Status == 1);
            if (warehouseobj == null)
            {
                message = "库房不存在或已被禁用!";
                return false;
            }

            //获取所有巷道
            var routewayQuery = _routewayRepository.GetEntityWhereAll(x => x.WhId == wid && x.Status == 1 && x.Code != "routeway01");
            if (!routewayQuery.Any())
            {
                message = "无可用巷道!";
                return false;
            }
            List<long> enabledRoutewayIds = routewayQuery.Select(t => t.Id).ToList();//只取巷道id
                                                                                     // 获取所有货架
            var shelves = _shelfRepository.GetEntityWhereAll(x => x.WhId == wid && x.AreaId == areaobj.Id && x.Status == 1 && enabledRoutewayIds.Contains(x.RoutewayId ?? 0) && (x.Code == "shelf07" || x.Code == "shelf08" || x.Code == "shelf09" || x.Code == "shelf10"));
            if (!shelves.Any())
            {
                message = "无可用货架!";
                return false;
            }
            List<long> enabledShelves = shelves.Select(t => t.Id).ToList();//只取货架id
                                                                           //获取所有仓位
            var cellQuery = _cellRepository.GetEntityWhereAll(x => x.AreaCode == acode && x.Status == 1 && x.FullStatus == 0 && x.IsLock == false && x.BusinessType == 0 && enabledRoutewayIds.Contains(x.RoutewayId ?? 0) && enabledShelves.Contains(x.ShelfId ?? 0) && x.ColumnNo == 1);
            if (!cellQuery.Any())
            {
                message = "无可用仓位!";
                return false;
            }
            cellobj = cellQuery.Where(x => x.IsMaxDepth == true).OrderByDescending(c => c.DepthIndex)
                                .ThenBy(c => c.LayerNo)
                                .ThenBy(c => c.ColumnNo)
                                .ThenBy(c => c.LineNo)
                                .FirstOrDefault();
            if (cellobj != null)
            {
                message = cellobj.Code;
                return true;
            }
            else
            {
                cellobj = cellQuery.Where(x => x.IsMaxDepth == false).OrderByDescending(c => c.DepthIndex)
                              .ThenBy(c => c.LayerNo)
                              .ThenBy(c => c.ColumnNo)
                              .ThenBy(c => c.LineNo)
                              .FirstOrDefault();
                if (cellobj != null)
                {
                    message = cellobj.Code;
                    return true;
                }
            }
            if (cellobj == null)
                message = "无可用仓位!";
            return false;
        }
        /// <summary>
        /// 兄弟仓位
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool GetCellCode(StackingStorage m,string stockcode, out string message)
        {
            message = string.Empty;
            if (string.IsNullOrEmpty(m.AreaCode))
            {
                message = "库区编码有误！";
                return false;
            }
            //获取所有库区
            var areaobj = _areaRepository.QueryIsEntityWhere(x => x.Code == m.AreaCode && x.Status == 1);
            if (areaobj == null || areaobj.WhId == null)
            {
                message = "库区不存在或已被禁用!";
                return false;
            }
            long? wid = areaobj.WhId;
            //获取所有库房
            var warehouseobj = _warehouseRepository.QueryIsEntityWhere(x => x.Id == wid && x.Status == 1);
            if (warehouseobj == null)
            {
                message = "库房不存在或已被禁用!";
                return false;
            }

            //获取所有巷道
            var routewayQuery = _routewayRepository.GetEntityWhereAll(x => x.WhId == wid && x.Status == 1);
            if (!routewayQuery.Any())
            {
                message = "无可用巷道!";
                return false;
            }
            var allroutewayid = routewayQuery.Select(x => x.Id).ToList();
            allroutewayid = allroutewayid.OrderByDescending(x => x).ToList();
            foreach (var rid in allroutewayid)
            {
                //获取所有货架
                var shelves = _shelfRepository.GetEntityWhereAll(x => x.WhId == wid && x.AreaId == areaobj.Id && x.Status == 1 && x.RoutewayId == rid);
                if (!shelves.Any())
                {
                    message = "无可用货架!";
                    continue;
                }
                List<long> enabledShelves = shelves.Select(t => t.Id).ToList();//只取货架id
                var groupcode = string.Empty;
                if (!string.IsNullOrEmpty(stockcode))
                {
                    var stock = stockRepository.QueryEntityWhere(d => d.StockCode == stockcode);
                    if (stock.IsSPManage == 0 && m.AreaCode.Contains("P"))
                    {
                        //无仓组时的仓位 
                        message = "Cell:2_1_1_1_1";
                        return true;
                    }
                    else
                    {
                        groupcode = stock.SPGroupCode;
                    }
                }
                

                var allcell = _cellRepository.GetEntityWhereAll(x => enabledShelves.Contains(x.ShelfId ?? 0) && x.Status == 1 && x.FullStatus == 0 && x.BusinessType == 0 && x.IsLock == false).ToList();
                if (!string.IsNullOrEmpty(groupcode))
                {
                    allcell = allcell.Where(x => x.SPGroupCode == groupcode).ToList();
                }
                int ycount = 0;
                int ncount = 0;
                long routewayid = 0;
                //默认找最深的
                bool ismaxdepth = true;
                ycount = allcell.Where(x => x.RoutewayId == rid && x.IsMaxDepth == true).Count();
                ncount = allcell.Where(x => x.RoutewayId == rid && x.IsMaxDepth == false).Count();
                //深的2个 浅的是1个
                if (ycount <= 1)
                {
                    if (ncount <= 1)
                        continue;
                    ismaxdepth = false;
                    routewayid = rid;
                }
                else
                {
                    routewayid = rid;
                }
                if (routewayid == 0)
                {
                    message = "无可用仓位！";
                    continue;
                }

                #region 兄弟仓位
                var invlist = _inventoryRepository.GetEntityWhereAll(x => x.MaterialId == m.MaterialId && x.BatchNo == m.BatchNo&&x.AreaCode== areaobj.Code && x.LocationDistanceValue == 1 && x.Status == 1 && x.IsLock == false && x.RoutewayId == routewayid);
                if (invlist.Any()&& areaobj.Code.Contains("P"))
                {
                    var firstInventory = invlist.FirstOrDefault();
                    if (firstInventory != null)
                    {
                        message = firstInventory.LocationCode;
                        return true;
                    }
                    else
                    {
                        message = "平库无符合条件的仓位";
                        return false;
                    }
                } 
                if (invlist.Any() && ncount > 1)
                {
                    foreach (var item in invlist.ToList())
                    {
                        //排
                        //string rows = item.LocationCode.Substring(7, 1);
                        string[] parts12 = item.LocationCode.Split('_');
                        string rows = parts12[1];
                        if (string.IsNullOrEmpty(rows))
                        {
                            message = "获取仓位排失败！";
                            continue;
                        }
                        if (rows == "1")
                        {
                            string[] parts = item.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_2_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = modifiedcellcode;
                                return true;
                            }
                        }
                        else if (rows == "5")
                        {
                            string[] parts = item.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_4_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = modifiedcellcode;
                                return true;
                            }
                        }
                        else if (rows == "6")
                        {
                            string[] parts = item.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_7_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = modifiedcellcode;
                                return true;
                            }
                        }
                        else if (rows == "10")
                        {
                            string[] parts = item.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_9_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = modifiedcellcode;
                                return true;
                            }
                        }
                        else if (rows == "11")
                        {
                            string[] parts = item.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_12_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = modifiedcellcode;
                                return true;
                            }
                        }
                        else if (rows == "15")
                        {
                            string[] parts = item.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_14_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = modifiedcellcode;
                                return true;
                            }
                        }
                    }
                }

                #endregion
                var cellQuery = _cellRepository.GetEntityWhereAll(x => x.AreaCode == m.AreaCode && x.Status == 1 && x.FullStatus == 0 && x.IsLock == false && x.BusinessType == 0  && enabledShelves.Contains(x.ShelfId ?? 0));
                if (!string.IsNullOrEmpty(groupcode))
                {
                    cellQuery = cellQuery.Where(x => x.SPGroupCode == groupcode);
                }
                if (!cellQuery.Any())
                {
                    message = "无可用仓位!";
                    continue;
                }
                if (ismaxdepth)
                {
                    var cellsIsMaxDepths = cellQuery.Where(x => x.IsMaxDepth == true).OrderByDescending(c => c.DepthIndex)
                                  .ThenBy(c => c.LayerNo)
                                  .ThenBy(c => c.ColumnNo)
                                  .ThenBy(c => c.LineNo).ToList();
                    foreach (var item in cellsIsMaxDepths)
                    {
                        //排
                        //string rows = Substring(7, 1);
                        string[] parts12 = item.Code.Split('_');
                        string rows = parts12[1];
                        if (string.IsNullOrEmpty(rows))
                        {
                            message = "获取仓位排失败！";
                            continue;
                        }
                        if (rows == "1")
                        {
                            string[] parts = item.Code.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_2_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = item.Code;
                                return true;
                            }
                        }
                        else if (rows == "5")
                        {
                            string[] parts = item.Code.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_4_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = item.Code;
                                return true;
                            }
                        }
                        else if (rows == "6")
                        {
                            string[] parts = item.Code.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_7_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = item.Code;
                                return true;
                            }
                        }
                        else if (rows == "10")
                        {
                            string[] parts = item.Code.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_9_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = item.Code;
                                return true;
                            }
                        }
                        else if (rows == "11")
                        {
                            string[] parts = item.Code.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_12_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = item.Code;
                                return true;
                            }
                        }
                        else if (rows == "15")
                        {
                            string[] parts = item.Code.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_14_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = item.Code;
                                return true;
                            }
                        }
                    }
                }
                var cellsIsMaxDepths2 = cellQuery.Where(x => x.IsMaxDepth == false).OrderByDescending(c => c.DepthIndex)
                             .ThenBy(c => c.LayerNo)
                             .ThenBy(c => c.ColumnNo)
                             .ThenBy(c => c.LineNo).ToList();
                if (cellsIsMaxDepths2.Any() && areaobj.Code.Contains("P"))
                {
                    var firstInventory = cellsIsMaxDepths2.FirstOrDefault();
                    if (firstInventory != null)
                    {
                        message = firstInventory.Code;
                        return true;
                    }
                    else
                    {
                        message = "平库无符合条件的仓位";
                        return false;
                    }
                }
                foreach (var item in cellsIsMaxDepths2)
                {
                    //排
                    //string rows = item.Code.Substring(7, 1);
                    string[] parts12 = item.Code.Split('_');
                    string rows = parts12[1];
                    if (string.IsNullOrEmpty(rows))
                    {
                        message = "获取仓位排失败！";
                        continue;
                    }
                    if (rows == "2")
                    {
                        string[] parts = item.Code.Substring(5).Split(separator: '_');
                        int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                        int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                        int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                        int lev = Convert.ToInt32(parts[3]);  // 层是第
                        string modifiedcellcode = $"Cell:{rou}_1_{col}_{lev}_2";
                        var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                        if (inventorycell != null && inventorycell.Status == 1)
                        {
                            message = item.Code;
                            return true;
                        }
                        else
                            continue;
                    }
                    else if (rows == "4")
                    {
                        string[] parts = item.Code.Substring(5).Split(separator: '_');
                        int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                        int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                        int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                        int lev = Convert.ToInt32(parts[3]);  // 层是第
                        string modifiedcellcode = $"Cell:{rou}_5_{col}_{lev}_2";
                        var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                        if (inventorycell != null && inventorycell.Status == 1)
                        {
                            message = item.Code;
                            return true;
                        }
                        else
                            continue;
                    }
                    else if (rows == "7")
                    {
                        string[] parts = item.Code.Substring(5).Split(separator: '_');
                        int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                        int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                        int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                        int lev = Convert.ToInt32(parts[3]);  // 层是第
                        string modifiedcellcode = $"Cell:{rou}_6_{col}_{lev}_2";
                        var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                        if (inventorycell != null && inventorycell.Status == 1)
                        {
                            message = item.Code;
                            return true;
                        }
                        else
                            continue;
                    }
                    else if (rows == "9")
                    {
                        string[] parts = item.Code.Substring(5).Split(separator: '_');
                        int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                        int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                        int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                        int lev = Convert.ToInt32(parts[3]);  // 层是第
                        string modifiedcellcode = $"Cell:{rou}_10_{col}_{lev}_2";
                        var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                        if (inventorycell != null && inventorycell.Status == 1)
                        {
                            message = item.Code;
                            return true;
                        }
                        else
                            continue;
                    }
                    else if (rows == "12")
                    {
                       
                        string[] parts = item.Code.Substring(5).Split(separator: '_');
                        int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                        int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                        int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                        int lev = Convert.ToInt32(parts[3]);  // 层是第
                        string modifiedcellcode = $"Cell:{rou}_11_{col}_{lev}_2";
                        var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                        if (inventorycell != null && inventorycell.Status == 1)
                        {
                            message = item.Code;
                            return true;
                        }
                        else
                            continue;
                    }
                    else if (rows == "14")
                    {
                        string[] parts = item.Code.Substring(5).Split(separator: '_');
                        int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                        int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                        int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                        int lev = Convert.ToInt32(parts[3]);  // 层是第
                        string modifiedcellcode = $"Cell:{rou}_15_{col}_{lev}_2";
                        var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                        if (inventorycell != null && inventorycell.Status == 1)
                        {
                            message = item.Code;
                            return true;
                        }
                        else
                            continue;
                    }
                }
            }
            message = "无可用仓位!";
            return false;
        }
        #endregion

        #endregion

        #region PC
        //public List<ReceivingOrderDetailDto> GetReceivingOrderDetailList(DateTime? startTime, DateTime? endTime, string? orderSn, int status, int pageIndex, int pageSize, out int totalCount)
        //{
        //    var list = _receivingOrderDetailRepository.GetEntityAlls();
        //    //入库单号
        //    if (!string.IsNullOrEmpty(orderSn))
        //    {
        //        list = list.Where(x => x.OrderSn.Contains(orderSn));
        //    }

        //    if (status < 8)
        //    {
        //        list = list.Where(x => x.Status == status);
        //    }

        //    if (startTime != null && endTime != null)
        //    {
        //        list = list.Where(s => s.CreateDate.Date >= startTime && s.CreateDate.Date <= endTime);
        //    }
        //    else if (endTime != null)
        //    {
        //        list = list.Where(s => s.CreateDate.Date <= endTime);
        //    }
        //    else if (startTime != null)
        //    {
        //        list = list.Where(s => s.CreateDate.Date >= startTime);
        //    }
        //    totalCount = list.Count();

        //    var materpacklist = _materialPackageRepository.GetEntityAlls().ToList();
        //    List<ReceivingOrderDetailDto> receivingOrderDetailDtos = new List<ReceivingOrderDetailDto>();
        //    foreach (var item in list)
        //    {
        //        ReceivingOrderDetailDto receivingOrderDetailDto = new ReceivingOrderDetailDto();
        //        receivingOrderDetailDto = mapper.Map<ReceivingOrderDetailDto>(item);
        //        var ordersn = _receivingBillRepository.QueryEntityWhere(d => d.BillNo == item.OrderSn);
        //        if (ordersn.BillType == 1)
        //        {
        //            receivingOrderDetailDto.ErpBillType = "采购入库";
        //        }else if (ordersn.BillType == 2)
        //        {
        //            receivingOrderDetailDto.ErpBillType = "生产入库";
        //        }
        //        else if (ordersn.BillType == 3)
        //        {
        //            receivingOrderDetailDto.ErpBillType = "VIM入库";
        //        }
        //        else if (ordersn.BillType == 4)
        //        {
        //            receivingOrderDetailDto.ErpBillType = "调拨单";
        //        }
        //        else if (ordersn.BillType == 5)
        //        {
        //            receivingOrderDetailDto.ErpBillType = "其他入库";
        //        }
        //        else if (ordersn.BillType == 6)
        //        {
        //            receivingOrderDetailDto.ErpBillType = "生产退料";
        //        }

        //        var materpackobj = materpacklist.FirstOrDefault(x => x.MaterialId == item.MaterialId);
        //        if (materpackobj != null)
        //        {
        //            if (item.AreaCode.Contains('P'))
        //                receivingOrderDetailDto.Qty = receivingOrderDetailDto.Qty / materpackobj.ConversionFactor;
        //            else
        //                receivingOrderDetailDto.UnitName = materpackobj.SubPackageUnitName;
        //        }
        //        receivingOrderDetailDto.CreateDates = item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");
        //        receivingOrderDetailDtos.Add(receivingOrderDetailDto);
        //    }
        //    return receivingOrderDetailDtos.OrderByDescending(x => x.CreateDates).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        //}
        public List<ReceivingOrderDetailDto> GetReceivingOrderDetailList(DateTime? startTime, DateTime? endTime, string? orderSn, int status, int pageIndex, int pageSize, out int totalCount)
        {
            var query = _receivingOrderDetailRepository.GetEntityAlls();

            if (!string.IsNullOrEmpty(orderSn))
            {
                query = query.Where(x => x.OrderSn.Contains(orderSn));
            }

            if (status < 8)
            {
                query = query.Where(x => x.Status == status);
            }

            if (startTime != null && endTime != null)
            {
                query = query.Where(s => s.CreateDate.Date >= startTime && s.CreateDate.Date <= endTime);
            }
            else if (endTime != null)
            {
                query = query.Where(s => s.CreateDate.Date <= endTime);
            }
            else if (startTime != null)
            {
                query = query.Where(s => s.CreateDate.Date >= startTime);
            }

            // 计算总记录数
            totalCount = query.Count();

            // 应用分页并立即执行查询，将结果加载到内存
            var pagedList = query.OrderByDescending(x => x.CreateDate)
                                .Skip((pageIndex - 1) * pageSize)
                                .Take(pageSize)
                                .ToList(); // 物化分页结果，关闭DataReader

            var materpacklist = _materialPackageRepository.GetEntityAlls().ToList();
            List<ReceivingOrderDetailDto> receivingOrderDetailDtos = new List<ReceivingOrderDetailDto>();

            foreach (var item in pagedList) // 遍历分页后的结果
            {
                ReceivingOrderDetailDto dto = mapper.Map<ReceivingOrderDetailDto>(item);

                // 查询关联的ReceivingBill
                var orderBill = _receivingBillRepository.QueryEntityWhere(d => d.BillNo == item.OrderSn);
                var inventory = _inventoryRepository.QueryEntityWhere(d => d.RelatedOrderDetailId == item.Id);
                // 确保使用SingleOrDefault或FirstOrDefault以避免潜在异常
                // var orderBill = _receivingBillRepository.GetEntityAlls().FirstOrDefault(d => d.BillNo == item.OrderSn);

                if (orderBill != null)
                {
                    dto.ErpBillType = orderBill.BillType switch
                    {
                        1 => "采购订单",
                        2 => "收料通知单",
                        3 => "生产任务单",
                        4 => "调拨单",
                        5 => "其他入库",
                        _ => dto.ErpBillType
                    };
                    dto.Receiver = orderBill.Receiver;
                    dto.Remark = orderBill.StockName;
                }

                var materpackobj = materpacklist.FirstOrDefault(x => x.MaterialId == item.MaterialId);
                if (materpackobj != null)
                {
                    if (item.AreaCode.Contains('P'))
                        // dto.Qty /= materpackobj.ConversionFactor;
                        dto.Qty = item.Qty;
                    else
                        dto.UnitName = materpackobj.SubPackageUnitName;
                }

                dto.CreateDates = item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");
                receivingOrderDetailDtos.Add(dto);
            }

            // 由于已提前分页，此处无需再次分页
            return receivingOrderDetailDtos;
        }


        //public async Task<bool> ModifyOutOrderNoAsync(List<ReceivingOrderDetailDto> dt)
        //{
        //    foreach (var item in dt)
        //    {
        //        var receiningOrderDetail = await _receivingOrderDetailRepository.GetAsync(d => d.LocationName == item.LocationName);

        //        if (receiningOrderDetail != null)
        //        {
        //            receiningOrderDetail.OutOrderNo = "已同步";
        //            await _receivingOrderDetailRepository.UpdateAsync(receiningOrderDetail);
        //        }
        //        else
        //        {

        //            return false;
        //        }
        //    }

        //    return _unitOfWork.SaveChangesEntity();


        //}
        public bool ModifyOutOrderNo(List<ReceivingOrderDetailDto> dt)
        {
            foreach (var item in dt)
            {
                var receiningOrderDetail =  _receivingOrderDetailRepository.QueryEntityWhere(d => d.LocationName == item.LocationName);

                if (receiningOrderDetail != null)
                {
                    receiningOrderDetail.OutOrderNo = "已同步";
                     _receivingOrderDetailRepository.UpdateAsync(receiningOrderDetail);
                }
                else
                {

                    return false;
                }
            }

            return _unitOfWork.SaveChangesEntity();
        }

        public WcsTaskResultDto? GetLocationCodeByPalletCode(string palletCode, out string message)
        {
            var putobj = _putawayOrderRepository.QueryEntityWhere(x => x.PalletBarcode == palletCode && x.SourceType == 1 && x.Status == 4);
            message = string.Empty;
            if (putobj != null)
            {
                return new WcsTaskResultDto
                {
                    ReturnStatus = 0,
                    ReturnInfo = putobj.LocationCode,
                    MsgTime = DateTime.Now.ToString()
                };
            }
            return new WcsTaskResultDto
            {
                ReturnStatus = 1,
                ReturnInfo = "找不到任务！",
                MsgTime = DateTime.Now.ToString()
            };
        }

        public WcsTaskResultDto? GetPalletMaterialCodeBySlide(TaskReceivingDto m, out string message)
        {
            throw new NotImplementedException();
        }
        #endregion
    }
}
